Is there a way in ASP.NET MVC to handle different Response.StatusCode values?

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:

// using the IAuthorizationFilter allows us to use the base controller 
//   built attribute handling.  We could have used result as well, but Auth seems
//   more appropriate.
public class ActiveAccountAttribute: FilterAttribute, IAuthorizationFilter
{

    #region IAuthorizationFilter Members

    public void OnAuthorization(AuthorizationContext filterContext)
    {

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            return;

        // ... code which determines if our customer account is Active

        if (!user.Status.IsActive)
            filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new {controller = "Account"}));
    }

    #endregion
}
+3
source share
2 answers

You can inherit the class RedirectToRouteResultand add a constructor parameter for the status code.

public class StatusRedirectResult : RedirectToRouteResult

    private string _status;

    public StatusRedirectResult(string action, RouteValueDictionary routeValues, string statusCode)
    {
        _status = statusCode;
        base.RedirectToRouteResult(action, routeValues);
    }

    public override ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Current.Response.Status = _status;
        base.ExecuteResult(context);
    }
}

To use this in a controller action, simply

return StatusRedirect("NewAction", new RouteValueDictionary(new { controller = "TheController" }, "410");
+3
source

.

Response.StatusCode = (int)HttpStatusCode.NotFound;

<customErrors mode="On">
     <error statusCode="404" redirect="~/Profile/Update" />
</customErrors>
0

Source: https://habr.com/ru/post/1717187/


All Articles