asp.net mvc authorize attribute redirect

asp.net-mvc, c#

Solution

You should override `HandleUnauthorizedRequest`

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    base.HandleUnauthorizedRequest(filterContext);

    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "xxx", action = "xxx", area = "" }));
}

Problem

In my application I have made a custom Attribute like this ``` public class AdminAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized || Auth.CurrentAdminUser == null) { return false; } else { return (SuperAdmin.Get(Auth.CurrentAdminUser.Id) != null) ? true : false; } } } ``` It is working fine, but what I want is to do a redirect based on if the user is not logged in then take to log in page and if the user is logged in but is not a super admin take him to not authorize page. What happens now is that all the unauthorized stuff is redirected to this page through web.config file, ``` <authentication mode="Forms"> <forms loginUrl="~/Site/NotAuthorize" timeout="2880" /> <!-- this is where we can set up that if you are not authenticated, where should you go then?--> </authentication> ``` Any help would be much appreciated.

Original source