In my ASP.NET MVC app, I have most controllers decorated with
[Authorize(Roles=\"SomeGroup\")]
When a user is not authorized to access som
You can look for the ?ReturnUrl= querystring value, or you can create your own authorization filter & set a field in TempData indicating the reason.
Here is a simple custom filter that will do the trick:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
// NOTE: This is not thread safe, it is much better to store this
// value in HttpContext.Items. See Ben Cull's answer below for an example.
private bool _isAuthorized;
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
_isAuthorized = base.AuthorizeCore(httpContext);
return _isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if(!_isAuthorized)
{
filterContext.Controller.TempData.Add("RedirectReason", "Unauthorized");
}
}
}
Then in your view, you can do something like this:
@if(TempData["RedirectReason"] == "Unauthorized")
{
You don't have permission to access that area
}
(Though I'd recommend a better approach than these magic strings, but you get the point)