By default, the MVC authorization attribute sets HttpContext.Response.StatusCode = 401 when the user is not authorized and the section in the web.config routes matches the loginUrl property.
I want to do something similar with other response codes. For example, I have an attribute called ActiveAccount that validates the user account currently and then allows them to access the controller. If they are inactive, I want to redirect them to a specific controller and view (to update their account).
I would like to copy the Authorize attributes for this and set the StatusCode to something like 410 (warning: previous number was out of thin air) and redirect the user to the location defined in the web.config file.
What can I do to implement this behavior? Or is there an easier method?
Edit: Results
I ended up avoiding the StatusCode and just doing the redirection from the attribute, as that was a lot easier. Here is my code in a nutshell:
public class ActiveAccountAttribute: FilterAttribute, IAuthorizationFilter
{
#region IAuthorizationFilter Members
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
return;
if (!user.Status.IsActive)
filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new {controller = "Account"}));
}
#endregion
}
source
share