ASP.NET MVC - How to show unauthorized error on login page?

后端 未结 7 2038
花落未央
花落未央 2020-11-28 02:58

In my ASP.NET MVC app, I have most controllers decorated with

[Authorize(Roles=\"SomeGroup\")]

When a user is not authorized to access som

7条回答
  •  萌比男神i
    2020-11-28 03:20

    You can look for the ?ReturnUrl= querystring value, or you can create your own authorization filter & set a field in TempData indicating the reason.

    Here is a simple custom filter that will do the trick:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
    
        // NOTE: This is not thread safe, it is much better to store this
        // value in HttpContext.Items.  See Ben Cull's answer below for an example.
        private bool _isAuthorized;
    
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            _isAuthorized = base.AuthorizeCore(httpContext);
            return _isAuthorized;
        }
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
    
            if(!_isAuthorized)
            {
                filterContext.Controller.TempData.Add("RedirectReason", "Unauthorized");
            }
        }
    }
    

    Then in your view, you can do something like this:

    @if(TempData["RedirectReason"] == "Unauthorized")
    {
        You don't have permission to access that area
    }
    

    (Though I'd recommend a better approach than these magic strings, but you get the point)

提交回复
热议问题