每个系统使用的权限控制方式都不一样,自定义鉴权Attribute,可以方便快速的进行处理。
public class AppAuthorizeAttribute : AuthorizeAttribute { /// <summary> /// 登陆页面 /// </summary> public class PageUrl { public string Controller { get; set; } public string Action { get; set; } public string Url { get { return string.Format("{0}/{1}", Controller, Action); } } } private PageUrl url; public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } //获取当前页面地址 url = new PageUrl(); url.Controller = filterContext.RouteData.Values["controller"] as string; url.Action = filterContext.RouteData.Values["action"] as string; //判断用户是否登录 if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // 未登录,跳转至登录页面 filterContext.Result = new HttpUnauthorizedResult(); return; } else { if (!AuthorizeCore(filterContext.HttpContext)) { filterContext.Result = new RedirectResult("/Error/Index/您无权访问该页面,请联系管理员"); } //redirect to login page } } /// <summary> /// 覆寫AuthorizeAttribute類別的AuthorizeCore方法 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { bool result = false; if (httpContext.User.Identity.IsAuthenticated) { //进行权限校验 //if(。。。。。) result = true; } return result; }
使用:
[AppAuthorizeAttribute()] public ViewResult Index() { return View() }