ASP.NET MVC - How to show unauthorized error on login page?

Viewed 38014

In my ASP.NET MVC app, I have most controllers decorated with

[Authorize(Roles="SomeGroup")]

When a user is not authorized to access something, they are sent to "~/Login" which is the Login action on my Account controller.

How can I determine that a user has reached the login page because of not being authorized so that I can show an appropriate error?

7 Answers

Going further from divide_byzero's answer even if you don't have a controller you can still use the HandleUnauthorizedRequest to change the redirect.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AuthoriseRedirect : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.RequestContext.HttpContext.Response.Redirect("UrlToRedirectTo");
        }
    }

Comes in handy if you have a legacy webforms site that you will be converting to MVC over a longer period of time.....!

Related