【问题标题】:ASP.Net MVC5: How to redirect and show right error message when user does not have a specific role for actionASP.Net MVC5:当用户没有特定的操作角色时如何重定向并显示正确的错误消息
【发布时间】:2016-09-21 22:35:56
【问题描述】:

登录后用户可以进行任何操作,但要考虑何时使用授权属性修饰操作并且角色名称在那里是特定的。只需参考示例代码。

public class HomeController : Controller
 {
     [Authorize(Roles = "Admin, HrAdmin")]
     public ActionResult PayRoll()
     {
         return View();
     }
 }

假设用户 Foo 没有像 Admin 或 HRAdmin 这样的角色,那么当用户 foo 尝试访问 PayRoll 操作时会发生什么?

在这种情况下,我想将用户重定向到我的错误页面,在那里我将向用户显示一条友好的消息。请指导我怎么做?

我是否需要从那里编写自定义授权属性,我需要检查用户是否有这些角色,然后从那里重定向用户?

【问题讨论】:

    标签: asp.net-mvc-5


    【解决方案1】:

    我不知道这是否是最好的方法,但我是这样做的:

    using System.Web.Mvc;
    
    namespace YourNamespace
    {
        public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
        {
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                base.OnAuthorization(filterContext);
    
                // Redirect to the login page if necessary
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" + filterContext.HttpContext.Request.Url);
                    return;
                }
    
                // Redirect to your "access denied" view here
                if (filterContext.Result is HttpUnauthorizedResult)
                {
                    filterContext.Result = new RedirectResult("~/Account/Denied");
                }
            }
        }
    }
    

    控制器:

    public class HomeController : Controller
    {
        [AccessDeniedAuthorize(Roles = "Admin, HrAdmin")]
        public ActionResult PayRoll()
        {
            return View();
        }
    }
    

    如果您的用户的角色定义正确,这就是您所要做的一切。如果您没有使用 ASP.NET Identity 来管理您的用户和角色,则需要更多代码来完成这项工作,在这种情况下,这可能会对您有所帮助:How can I attach a custom membership provider in my ASP.NET MVC application?

    【讨论】:

    • 给我完整的代码,比如如何在我的情况下使用它,比如如果用户没有像管理员或 HRAdmin 这样的角色,那么我会将用户重定向到自定义错误页面,在那里我会向他显示一条友好的消息。跨度>
    • 你需要像这样使用属性:[AccessDeniedAuthorize(Roles = "Admin, HrAdmin")]。它的工作方式与 Authorize 属性完全相同。
    • 如何检查用户是否拥有 Admin、HrAdmin 角色或其中任何一个角色,或者不只是从数据库中获取用户角色?您可以添加更多代码来制作完整的示例吗?谢谢
    • 您不需要做任何其他事情,就像您在问题中写的那样将属性添加到您的方法中。我将编辑我的答案给你看。
    • 您使用的是 ASP.NET Identity 吗?如果您正在使用它,则不需要从数据库中获取您的角色,它们已经填充到您的 User 对象中,并且它们将自动与您在 Roles = "Admin, HrAdmin, [...]" 中输入的内容进行比较。
    猜你喜欢
    • 2015-11-04
    • 2013-04-04
    • 2012-05-08
    • 2023-03-06
    • 2021-08-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多