解决方法
这是从我修改的AuthorizeAttribute实现的代码;我把它命名为SecurityAttribute。我唯一改变的是OnAuthorization方法,我添加了一个额外的字符串属性为Url重定向到一个未经授权的页面:
// Set default Unauthorized Page Url here private string _notifyUrl = "/Error/Unauthorized"; public string NotifyUrl { get { return _notifyUrl; } set { _notifyUrl = value; } } public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (AuthorizeCore(filterContext.HttpContext)) { HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; cachePolicy.SetProxyMaxAge(new TimeSpan(0)); cachePolicy.AddValidationCallback(CacheValidateHandler,null); } /// This code added to support custom Unauthorized pages. else if (filterContext.HttpContext.User.Identity.IsAuthenticated) { if (NotifyUrl != null) filterContext.Result = new RedirectResult(NotifyUrl); else // Redirect to Login page. HandleUnauthorizedRequest(filterContext); } /// End of additional code else { // Redirect to Login page. HandleUnauthorizedRequest(filterContext); } }
您以与原始AuthorizeAttribute相同的方式调用它,除了有一个额外的属性可以覆盖未经授权的页面网址:
// Use custom Unauthorized page: [Security (Roles="Admin,User",NotifyUrl="/UnauthorizedPage")] // Use default Unauthorized page: [Security (Roles="Admin,User")]