ASP.NET MVC3 Terminate action / controller in user attribute AuthorizeAttribute

How can I stop an action / controller without redirecting and return a response using statusCode only

public class MainAuthorizationFilter : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        ... [my Authorization login] ...

        if([Authorization fail])
        {
             if (filterContext.HttpContext.Request.IsAjaxRequest())
             {
                 filterContext.HttpContext.Response.StatusCode = 401;
                 // HERE I want stop executing action/controller because I want return only statusCode
             }
             else
             {
                  // In non-ajax request I just redirect me request and action/contoller isn't executed
                  filterContext.Result = new RedirectToRouteResult("Error", new RouteValueDictionary { { "errorCode", errorCode } });
             }
        }
    }

    base.OnAuthorization(filterContext);

}

[MainAuthorizationFilter]
public ActionResult CreateFolder(...)
{
   CreateFolder(...);
}
+5
source share
2 answers
filterContext.Result = new HttpStatusCodeResult(401, "String description here if you want");

HttpStatusCodeResult on MSDN

Please note that the auth forms module can intercept this and convert it to a redirect to your login page - not sure if this also applies to AJAX requests, I have not tried ...

+10
source

I would just end the answer like this:

public class MainAuthorizationFilter : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        ... [my Authorization login] ...

        if([Authorization fail])
        {
             if (filterContext.HttpContext.Request.IsAjaxRequest())
             {
                 filterContext.HttpContext.Response.StatusCode = 403;
                 filterContext.HttpContext.Response.End();

             }
             else
             {
                  // In non-ajax request I just redirect me request and action/contoller isn't executed
                  filterContext.Result = new RedirectToRouteResult("Error", new RouteValueDictionary { { "errorCode", errorCode } });
             }
        }
    }

    base.OnAuthorization(filterContext);

}
+2
source

All Articles