Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC3 Stop executing action/controller in custom AuthorizeAttribute

How I can stop executing action/controller without redirection, and only return Response with statusCode

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(...);
}
like image 328
David Horák Avatar asked Jul 19 '11 12:07

David Horák


1 Answers

filterContext.Result = new HttpStatusCodeResult(401, "String description here if you want");

HttpStatusCodeResult on MSDN

Note that the forms auth module may intercept this and convert it to a redirect to your login page - not sure if this applies to AJAX requests too, I haven't tried it...

like image 164
Jon Avatar answered Nov 14 '22 16:11

Jon