如何在没有重定向的情况下停止执行操作/控制器,并且仅返回带有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(...);
}
答案 0 :(得分:10)
filterContext.Result = new HttpStatusCodeResult(401, "String description here if you want");
请注意,表单auth模块可以拦截它并将其转换为重定向到您的登录页面 - 不确定这是否也适用于AJAX请求,我还没试过......
答案 1 :(得分:2)
我会简单地结束回复:
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);
}