参见英文答案 >
ASP.NET MVC – How to show unauthorized error on login page?7个答案我正在使用自定义授权属性来授权用户根据权限级别进行访问。我需要重定向未经授权的用户(例如,用户尝试删除没有删除访问级别的发票)来访问被拒绝的页面。
自定义属性正在工作。但是在未经授权的用户访问的情况下,浏览器中没有显示任何内容。
Contoller代码。
public class InvoiceController : Controller { [AuthorizeUser(AccessLevel = "Create")] public ActionResult CreateNewInvoice() { //... return View(); } [AuthorizeUser(AccessLevel = "Delete")] public ActionResult DeleteInvoice(...) { //... return View(); } // more codes/ methods etc. }
public class AuthorizeUserAttribute : AuthorizeAttribute { // Custom property public string AccessLevel { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { return false; } string privilegeLevels = string.Join("",GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB if (privilegeLevels.Contains(this.AccessLevel)) { return true; } else { return false; } } }
感谢您能分享您的经验。
解决方法
您必须按照
here规定覆盖HandleUnauthorizedRequest。
public class CustomAuthorize: AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if(!filterContext.HttpContext.User.Identity.IsAuthenticated) { base.HandleUnauthorizedRequest(filterContext); } else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new{ controller = "Error",action = "AccessDenied" })); } } }
**注意:更新的条件语句Jan ’16