I am using a custom authorize attribute in a ASP.NET MVC 5 application like following:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAuthenticated)
{
context.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
}
else
{
base.HandleUnauthorizedRequest(context);
}
}
}
In system.web
section of my web.config I mentioned error paths like:
<system.web>
<customErrors mode="On" defaultRedirect="/Error/Error">
<error statusCode="403" redirect="/Error/NoPermissions"/>
</customErrors>
</system.web>
But I am never redirected to my custom error page at /Error/NoPermissions
. Instead the browser display the general error page saying "HTTP Error 403.0 - Forbidden".
Thanks everyone, but problem is not with 403 code. Actually the problem was with the way i was trying to return 403. I just changed my code to throw an HttpException
instead of returning the HttpStatusCodeResult
and every things works now. I can return any HTTP status code by throwing HttpException
exception and my customErrors
configuration catches all of them. May be HttpStatusCodeResult
is not doing the exact job I expected it to do.
I just replaced
context.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
with
throw new HttpException((int)System.Net.HttpStatusCode.Forbidden, "Forbidden");
That's it.
Happy coding.