ASP.NET.4.5.1+MVC5.0系统角色和权限讲解
细说ASP.NET.4.5.1+MVC5.0系统角色和权限
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
1.在项目中新建文件夹Helpers
2.在HR.Helpers文件夹下添加EnumMoudle.Cs
namespace HR.Helpers
{
public enum EnumMoudle
{
/// <summary>
/// 模块 # codego.net#
/// </summary>
[EnumTitle("用户管理")]
SysUserManage_Role = 102,
[EnumTitle("机构管理")]
Department = 201,
[EnumTitle("人事资料")]
Employees = 301,
[EnumTitle("系统管理")]
BaseInfo = 404,
}
}
3.在HR.Helpers文件夹下添加ControllerBase.Cs
namespace HR.Helpers
{
public class ControllerBase : Controller
{
/// <summary>
/// 操作人,传IP....到后端记录
/// </summary>
public virtual Operater Operater
{
get
{
return null;
}
}
/// <summary>
/// 分页大小
/// </summary>
public virtual int PageSize
{
get
{
return 15;
}
}
protected ContentResult JsonP(string callback, object data)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
return this.Content(string.Format("{0}({1})", callback, json));
}
/// <summary>
/// 当弹出DIV弹窗时,需要刷新浏览器整个页面
/// </summary>
/// <returns></returns>
public ContentResult RefreshParent(string alert = null)
{
var script = string.Format("<script>{0}; parent.location.reload(1)</script>", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
return this.Content(script);
}
public new ContentResult RefreshParentTab(string alert = null)
{
var script = string.Format("<script>{0}; if (window.opener != null) {{ window.opener.location.reload(); window.opener = null;window.open('', '_self', ''); window.close()}} else {{parent.location.reload(1)}}</script>", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
return this.Content(script);
}
/// <summary>
/// 用JS关闭弹窗
/// </summary>
/// <returns></returns>
public ContentResult CloseThickbox()
{
return this.Content("<script>top.tb_remove()</script>");
}
/// <summary>
/// 警告并且历史返回
/// </summary>
/// <param name="notice"></param>
/// <returns></returns>
public ContentResult Back(string notice)
{
var content = new StringBuilder("<script>");
if (!string.IsNullOrEmpty(notice))
content.AppendFormat("alert('{0}');", notice);
content.Append("history.go(-1)</script>");
return this.Content(content.ToString());
}
public ContentResult PageReturn(string msg, string url = null)
{
var content = new StringBuilder("<script type='text/javascript'>");
if (!string.IsNullOrEmpty(msg))
content.AppendFormat("alert('{0}');", msg);
if (string.IsNullOrWhiteSpace(url))
url = Request.Url.ToString();
content.Append("window.location.href='" + url + "'</script>");
return this.Content(content.ToString());
}
/// <summary>
/// 转向到一个提示页面,然后自动返回指定的页面
/// </summary>
/// <param name="notice"></param>
/// <param name="redirect"></param>
/// <returns></returns>
public ContentResult Stop(string notice, string redirect, bool isAlert = false)
{
var content = "<meta http-equiv='refresh' content='1;url=" + redirect + "' /><body style='margin-top:0px;color:red;font-size:24px;'>" + notice + "</body>";
if (isAlert)
content = string.Format("<script>alert('{0}'); window.location.href='{1}'</script>", notice, redirect);
return this.Content(content);
}
/// <summary>
/// 在方法执行前更新操作人
/// </summary>
/// <param name="filterContext"></param>
public virtual void UpdateOperater(ActionExecutingContext filterContext)
{
if (this.Operater == null)
return;
WCFContext.Current.Operater = this.Operater;
}
public virtual void ClearOperater()
{
//TODO
}
/// <summary>
/// AOP拦截,在Action执行后
/// </summary>
/// <param name="filterContext">filter context</param>
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (!filterContext.RequestContext.HttpContext.Request.IsAjaxRequest() && !filterContext.IsChildAction)
RenderViewData();
this.ClearOperater();
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
this.UpdateOperater(filterContext);
base.OnActionExecuting(filterContext);
//在方法执行前,附加上PageSize值
filterContext.ActionParameters.Values.Where(v => v is Request).ToList().ForEach(v => ((Request)v).PageSize = this.PageSize);
}
/// <summary>
/// 产生一些视图数据
/// </summary>
protected virtual void RenderViewData()
{
}
/// <summary>
/// 当前Http上下文信息,用于写Log或其他作用
/// </summary>
public WebExceptionContext WebExceptionContext
{
get
{
var exceptionContext = new WebExceptionContext
{
IP = Fetch.UserIp,
CurrentUrl = Fetch.CurrentUrl,
RefUrl = (Request == null || Request.UrlReferrer == null) ? string.Empty : Request.UrlReferrer.AbsoluteUri,
IsAjaxRequest = (Request == null) ? false : Request.IsAjaxRequest(),
FormData = (Request == null) ? null : Request.Form,
QueryData = (Request == null) ? null : Request.QueryString,
RouteData = (Request == null || Request.RequestContext == null || Request.RequestContext.RouteData == null) ? null : Request.RequestContext.RouteData.Values
};
return exceptionContext;
}
}
/// <summary>
/// 发生异常写Log
/// </summary>
/// <param name="filterContext"></param>
protected override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
var e = filterContext.Exception;
LogException(e, this.WebExceptionContext);
}
protected virtual void LogException(Exception exception, WebExceptionContext exceptionContext = null)
{
//do nothing!
}
}
public class WebExceptionContext
{
public string IP { get; set; }
public string CurrentUrl { get; set; }
public string RefUrl { get; set; }
public bool IsAjaxRequest { get; set; }
public NameValueCollection FormData { get; set; }
public NameValueCollection QueryData { get; set; }
public RouteValueDictionary RouteData { get; set; }
}
}
4.在项目文件夹中新建ControllerBase.cs
namespace HR
{
public abstract class ControllerBase:HR.Helpers.ControllerBase
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}
}
5.在项目中新建RoleControllerBase.cs
namespace HR
{
public class RoleControllerBase : ControllerBase
{
SystemUserRepository sysuserrepository = new SystemUserRepository();
/// <summary>
/// 用户权限
/// </summary>
public virtual List<EnumMoudle> PermissionList
{
get
{
var permissionList = new List<EnumMoudle>();
return permissionList;
}
}
public string BusinessPermissionString { get; set; }
[NotMapped]
public List<EnumMoudle> BusinessPermissionList
{
get
{
if (string.IsNullOrEmpty(BusinessPermissionString))
return new List<EnumMoudle>();
else
return BusinessPermissionString.Split(",".ToCharArray()).Select(p => int.Parse(p)).Cast<EnumMoudle>().ToList();
}
set
{
BusinessPermissionString = string.Join(",", value.Select(p => (int)p));
}
}
/// <summary>
/// Action方法执行前没有权限提示信息
/// </summary>
/// <param name="filterContext"></param>
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var noAuthorizeAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeIgnoreAttribute), false);
if (noAuthorizeAttributes.Length > 0)
return;
base.OnActionExecuting(filterContext);
bool hasPermission = true;
var permissionAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>();
permissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast<PermissionAttribute>().Union(permissionAttributes);
var attributes = permissionAttributes as IList<PermissionAttribute> ?? permissionAttributes.ToList();
if (permissionAttributes != null && attributes.Count() > 0)
{
string cookie = CookieHelper.GetValue("SystemUserID");
if (string.IsNullOrEmpty(cookie))
{
filterContext.Result = Content("您没有登录!");
}
else
{
int mid = int.Parse(CookieHelper.GetValue("SystemUserID"));
var model = sysuserrepository.GetModel(mid);
BusinessPermissionString = model.BusinessPermissionString;
hasPermission = true;
foreach (var attr in attributes)
{
foreach (var permission in attr.Permissions)
{
if (!BusinessPermissionList.Contains(permission))
{
hasPermission = false;
break;
}
}
}
if (!hasPermission)
{
if (Request.UrlReferrer != null)
filterContext.Result = this.Stop("您没有权限!", "/default/ng");
else
filterContext.Result = Content("您没有权限!");
}
}
}
}
}
}
6.在每个Controller继承RoleControllerBase类
public class EmployeesController : RoleControllerBase
7.在HR.Helpers文件夹下添加PermissionAttribute.Cs ,并继承 FilterAttribute, IActionFilter
namespace HR.Helpers
{
public class PermissionAttribute : FilterAttribute, IActionFilter
{
public List<EnumMoudle> Permissions { get; set; }
public PermissionAttribute(params EnumMoudle[] parameters)
{
Permissions = parameters.ToList();
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
//throw new NotImplementedException();
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
//throw new NotImplementedException();
}
}
}
8.然后在Controller或者Action方法加上验证
[Permission(EnumMoudle.Employees),Authorize, ValidateInput(false)]
[Permission(EnumMoudle.SysUserManage_Role)]
9.在用户管理Controller中添加权限分配,修改方法
#region 添加管理员
/// <summary>
/// 添加页
/// </summary>
/// <param name="model">管理员实体类</param>
/// <returns></returns>
[Authorize]
public ActionResult Add()
{
var moudleList = EnumHelper.GetItemValueList<EnumMoudle>();
this.ViewBag.MoudleList = new SelectList(mouldeList, "Key", "Value");
return View();
}
/// <summary>
/// 添加事件
/// </summary>
/// <param name="model">实体类</param>
/// <param name="fc"></param>
/// <returns></returns>
[Authorize, HttpPost, ValidateInput(false)]
public ActionResult Add(SystemUser model, FormCollection fc)
{
model.BusinessPermissionString = fc["MoudelList"];
model.State = 1;
model.CreateTime = DateTime.Now;
systemuserrepository.SaveOrEditModel(model);
return RedirectToAction("UserList");
}
#endregion
//修改权限
[Authorize, AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public ActionResult Edit(int id, FormCollection fc)
{
var model = systemuserrepository.GetModel(id);
if (model != null)
{
string password = model.PassWord;
if (Request.Form["PassWord"] != "")
{
model.BusinessPermissionString = fc["MoudleList"];
UpdateModel(model);
systemuserrepository.SaveOrEditModel(model);
}
else
{
model.BusinessPermissionString = fc["MoudleList"];
UpdateModel(model);
model.PassWord = password;
systemuserrepository.SaveOrEditModel(model);
}
return RedirectToAction("userlist");
}
else
return View("404");
}
#endregion
[Authorize]
public ActionResult Edit(int id)
{
var model = systemuserrepository.GetModel(id);
if (model != null)
{
var moudleList = EnumHelper.GetItemValueList<EnumBusinessPermission>();
this.ViewBag.MoudleList = new SelectList(moudleList, "Key", "Value", string.Join(",", model.BusinessPermissionString.ToString()));
return View(model);
}
else
return View("404");
}
转载于:https://blog.51cto.com/10077983/1627643
ASP.NET.4.5.1+MVC5.0系统角色和权限讲解相关推荐
- android 权限作用说明书,AndroidAcp 一句话搞定,简化 Android 6.0 系统复杂的权限操作 @codeKK Android开源站...
Acp 为 Android check permission 缩写,此库简化 Android 6.0 系统复杂的权限操作而编写. 特点 支持批量权限申请,不需要重写 onRequestPermissi ...
- 华为android7.0 root,华为Nova 7.0 root教程 华为Nova获取7.0系统的root权限
刷机之家小编要说说咱们的华为Nova手机7.0系统的root教程了,这个root教程也是利用第三方的recovery来给手机刷入一个zip格式的root包就可以了, 这个root教程应用的也是比较普遍 ...
- 三星android 7.0 root,三星C7 Pro C7010 7.0 root教程_获取7.0系统的root权限
下面是有关这个三星C7 Pro C7010手机的具体的root操作了,这个root操作也是针对7.0的系统进行的,之前也有机友在问,咱们的这个手机的7.0系统该怎么进行root呢,可是网有关这个手机的 ...
- Spring security4.1.0 自定义角色和权限
文章大纲: 1.spring security 基本配置介绍 2.自定义角色和权限配置 3.跟着源码走一遍页面请求流程 spring security 基本配置介绍 首先需要创建一个为Spring s ...
- 主攻ASP.NET.4.5.1 MVC5.0之重生:Web项目语音朗读网页文本,简单语音提示浏览状态
第一步 添加SpeechLib.dll 下载SpeechLib.dll: 在项目中并且引用DLL using SpeechLib; using System.Threading; 第二步 调用并使用 ...
- 三星android获取root权限,三星S9 G9600 9.0 root教程_获取安卓9.0系统的root权限的方法...
不知道还有多少人在用这个三星S9 G9600手机的,并且想给咱们的这个手机进行root的呢,现在咱们的这个手机的最新的系统包也是安卓9.0版本的,对于这个安卓9.0的系统,相关的root操作一直没有给 ...
- 三星android 7.0 root,三星G9350 7.0 root教程_三星G9350获取7.0系统的root权限
咱们的三星G9350手机系统最新版本是安卓7.0的,这一节主要来说说咱们的手机这个手机如何进行root了,这个root操作也是针对7.0的系统进行操作的,因为7.0的系统和之前6.0的系统不同,用6. ...
- 三星android 7.0 root,三星G9350 7.0 root教程及获取7.0系统的root权限
咱们的三星G9350手机系统最新版本是安卓7.0的,这一节主要来说说咱们的手机这个手机如何进行root了,这个root操作也是针对7.0的系统进行操作的,因为7.0的系统和之前6.0的系统不同,用6. ...
- 三星android 7.0 root,三星GALAXY C5 C5000 7.0 root教程_获取7.0系统的root权限
之前给在说的有关三星GALAXY C5 C5000手机的root教程是针对6.0的系统的,今天在这里说的这个root操作是针对7.0的系统的,因为不少的机友已经把自己的手机系统升级到7.0的版本的,可 ...
最新文章
- Linux下CST和UTC时间的区别以及不一致的解决方法
- 大话设计模式(十一 三层架构,分层开发)
- 【总结】超1000页有三AI文档资源领取方法汇总!
- .NET新手系列(五)
- vml入门教程 【转】
- python如何定义类_Python class定义类,Python类的定义(入门必读)
- AsteriskNow 实用总结
- 乡镇街道边界数据、行政村边界、省市县区划边界、建筑轮廓边界数据、流域边界数据、降雨量分布、气温分布、道路网分布
- 高德地图输入地址获取经纬度_不打开地图也能获取地址-利用百度地图API和Python实现...
- 荣耀 android 11 rom,华为荣耀10官方固件rom刷机包_华为荣耀10完整版系统升级包
- OFFPIPE 海底管道铺设计算分析软件
- SQL创建数据库与写入数据的全过程
- 视频无法播放,视频打不开怎么办?可用这款视频修复工具快速修复
- 每一个都能笑抽的 39 个奇葩代码注释
- C语言反汇编 - 多维数组与指针
- 杜教筛如何推式子/堆柿子
- vscode终端无输出
- 安全测试简述/安全审计工具
- lenovo thinkpad t460s trackpiont小红点移动速度调整
- phpnow安装,phpnow卸载,phpnow教程,phpnow安装教程