重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
细说ASP.NET.4.5.1+MVC5.0系统角色和权限
成都创新互联是一家专业提供保靖企业网站建设,专注与成都网站设计、成都做网站、html5、小程序制作等业务。10年已为保靖众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
1.在项目中新建文件夹Helpers
2.在HR.Helpers文件夹下添加EnumMoudle.Cs
namespace HR.Helpers
{
public enum EnumMoudle
{
///
/// 模块 # codego.net#
///
[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
{
///
/// 操作人,传IP....到后端记录
///
public virtual Operater Operater
{
get
{
return null;
}
}
///
/// 分页大小
///
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));
}
///
/// 当弹出DIV弹窗时,需要刷新浏览器整个页面
///
///
public ContentResult RefreshParent(string alert = null)
{
var script = string.Format("", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
return this.Content(script);
}
public new ContentResult RefreshParentTab(string alert = null)
{
var script = string.Format("", string.IsNullOrEmpty(alert) ? string.Empty : "alert('" + alert + "')");
return this.Content(script);
}
///
/// 用JS关闭弹窗
///
///
public ContentResult CloseThickbox()
{
return this.Content("");
}
///
/// 警告并且历史返回
///
///
///
public ContentResult Back(string notice)
{
var content = new StringBuilder("");
return this.Content(content.ToString());
}
public ContentResult PageReturn(string msg, string url = null)
{
var content = new StringBuilder("");
return this.Content(content.ToString());
}
///
/// 转向到一个提示页面,然后自动返回指定的页面
///
///
///
///
public ContentResult Stop(string notice, string redirect, bool isAlert = false)
{
var content = "
" + notice + "";if (isAlert)
content = string.Format("", notice, redirect);
return this.Content(content);
}
///
/// 在方法执行前更新操作人
///
///
public virtual void UpdateOperater(ActionExecutingContext filterContext)
{
if (this.Operater == null)
return;
WCFContext.Current.Operater = this.Operater;
}
public virtual void ClearOperater()
{
//TODO
}
///
/// AOP拦截,在Action执行后
///
/// filter context
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);
}
///
/// 产生一些视图数据
///
protected virtual void RenderViewData()
{
}
///
/// 当前Http上下文信息,用于写Log或其他作用
///
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;
}
}
///
/// 发生异常写Log
///
///
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();
///
/// 用户权限
///
public virtual List
{
get
{
var permissionList = new List
return permissionList;
}
}
public string BusinessPermissionString { get; set; }
[NotMapped]
public List
{
get
{
if (string.IsNullOrEmpty(BusinessPermissionString))
return new List
else
return BusinessPermissionString.Split(",".ToCharArray()).Select(p => int.Parse(p)).Cast
}
set
{
BusinessPermissionString = string.Join(",", value.Select(p => (int)p));
}
}
///
/// Action方法执行前没有权限提示信息
///
///
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
permissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast
var attributes = permissionAttributes as IList
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
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 添加管理员
///
/// 添加页
///
/// 管理员实体类
///
[Authorize]
public ActionResult Add()
{
var moudleList = EnumHelper.GetItemValueList
this.ViewBag.MoudleList = new SelectList(mouldeList, "Key", "Value");
return View();
}
///
/// 添加事件
///
/// 实体类
///
///
[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
this.ViewBag.MoudleList = new SelectList(moudleList, "Key", "Value", string.Join(",", model.BusinessPermissionString.ToString()));
return View(model);
}
else
return View("404");
}