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

后端 未结 7 2046
花落未央
花落未央 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条回答
  •  醉酒成梦
    2020-11-28 03:16

    If you have a controller and don't want to have a url in you code you can redirect this way as well. It will not change the url in the address bar of the browser so the user will never see the url for the unauthorized page. This was written in MVC 3. This method will also work if you want to redirect them to a login page or if you want to redirect them to a page to just tell them they aren't authorized. I had section in the program that some user didn't have rights to but they were logged in so this is what I used.

    public class AuthorizedRedirect : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool isAuthorized = base.AuthorizeCore(httpContext);
            return isAuthorized;
        }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.RequestContext.RouteData.Values["controller"] = "error";
        filterContext.Result = new ViewResult { ViewName = "unauthorized" };
    }
    

提交回复
热议问题