Search code examples
c#asp.net-mvc-2http-status-code-403authorize-attribute

Is there a way to make AuthorizeAttribute respond with status code 403 Forbidden rather than a redirect?


If the user is not logged in and they request an action marked [Authorize], then the response is a redirect to the Account/LogOn action (status code 302 Found).

Is there a way to make the response be status code 403 Forbidden instead?


Solution

  • Create an action filter that inherits from AuthorizeAttribute. Then override this method:

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    { 
       Response.StatusCode = 403;
       Response.Status = "Forbidden";
       Response.StatusDescription = "Forbidden";
       Response.End();
       Response.Close();
    
    }