我正在尝试在一个新的ASP.NET MVC 5项目中实现访问被拒绝的错误页面,该项目使用单独用户账户认证模式。
我添加了一个CustomAuthorize
类,它继承自AuthorizeAttribute
。
public class CustomAuthorize : AuthorizeAttribute
{
protected virtual CustomPrincipal CurrentUser
{
get { return HttpContext.Current.User as CustomPrincipal; }
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
if (!string.IsNullOrEmpty(Roles))
{
if (!CurrentUser.IsInRole(Roles))
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
//base.OnAuthorization(filterContext); // returns to login url
}
}
if (!string.IsNullOrEmpty(Users))
{
if (!Users.Contains(CurrentUser.UserName))
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
//base.OnAuthorization(filterContext); // returns to login url
}
}
}
}
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" }));
}
}
}
添加 ErrorController.cs
public class ErrorController : Controller
{
public ActionResult AccessDenied()
{
return View();
}
}
还有AccessDenied.cshtml
视图
<h2>Access Denied</h2>
<p>You do not have access to view this page</p>
然后应用于HomeController.cs
[CustomAuthorize]
public class HomeController : Controller
然而它总是重定向到登录页面。如何显示访问被拒绝的页面?