ASP.NET – 如果角色授权失败,则重定向到错误页面

我正在使用MVC 3与表单身份validation。 在我的控制器或方法上,我正在执行以下操作:

[Authorize (Roles = "developer")] 

在这种情况下,我想检查用户是否已登录,如果没有,请将其返回登录页面。 但是,如果该用户的“IsInRole”检查返回false,我希望他们转到另一个类似“未授权”的视图。

完成这样的事情的最佳方法是什么? 我希望避免创建一个新的Authorization属性,所以我不必重构整个应用程序中的每个Authorize属性,但如果这是必需的,我将走这条路。

覆盖HandleUnauthorizedRequest方法的自定义授权属性可以完成以下任务:

 public class MyAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // The user is not authenticated base.HandleUnauthorizedRequest(filterContext); } else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) { // The user is not in any of the listed roles => // show the unauthorized view filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/Unauthorized.cshtml" }; } else { base.HandleUnauthorizedRequest(filterContext); } } } 

然后:

 [MyAuthorize(Roles = "developer")] public ActionResult Develop() { ... } 

您还可以使用401状态代码的自定义错误页面执行此操作。

有关实施细节,请参阅此问题 。

你可以像这样使用它。因为如果你没有权限它就是方法。 不需要授权控制

 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // The user is not authenticated base.HandleUnauthorizedRequest(filterContext); } else { filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/Unauthorized.cshtml", }; } }