How to make Authorize attribute return custom 403 error page instead of redirecting to the Logon page

后端 未结 2 1631
野的像风
野的像风 2020-12-04 13:21

[Authorize] attribute is nice and handy MS invention, and I hope it can solve the issues I have now

To be more specific:

When current client isn

2条回答
  •  心在旅途
    2020-12-04 13:37

    What I would do is subclass AuthorizeAttribute and override its HandleUnauthorizedRequest to return HTTP status code 403 if user is authenticated. I would then add a system.webServer\httpErrors section to my Web.Config to replace the default 403 with my custom page (this last part requires IIS 7+). Here's how:

    public class MyAuthorizeAttribute : AuthorizeAttribute {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                filterContext.Result = new HttpStatusCodeResult(403);
            else
                filterContext.Result = new HttpUnauthorizedResult();
        } 
    }
    
    
      
        
          
          
        
      
    
    

提交回复
热议问题