开发者

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

开发者 https://www.devze.com 2023-03-21 15:04 出处:网络
How I can stop executing action/controller without redirection, and only return Response with statusCode

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);

开发者_如何学C}

[MainAuthorizationFilter]
public ActionResult CreateFolder(...)
{
   CreateFolder(...);
}


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...


I would simply end the response like so:

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);

}
0

精彩评论

暂无评论...
验证码 换一张
取 消