ASP.NET MVC 4 custom Authorize attribute - How to redirect unauthorized users to error page? [duplicate]
You have to override the HandleUnauthorizedRequest
as specified here.
public class CustomAuthorize: AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if(!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
base.HandleUnauthorizedRequest(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new{ controller = "Error", action = "AccessDenied" }));
}
}
}
**Note: updated conditional statement Jan '16