![](/img/trans.png)
[英]Return a custom response body for 401 with Windows Authentication with MVC under IIS
[英]MVC 3 API custom response body on error
我正在尝试使用登录方法和其他方法编写API。 登录时出现问题时,我想使用自定义响应正文将自定义HTTP错误代码返回给客户端。 问题是错误时请求将被重定向到主页。
[HttpPost]
[AllowAnonymous]
public JsonResult ApiLogIn(LoginModel model)
{
if (ModelState.IsValid)
{
var outcome = _authService.LogIn(model);
if (outcome == LogInOutcome.Success)
{
return Json(new { }); // Empty on success
}
else
{
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Json(new { reason = outcome.ToString() });
}
}
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { }); // Empty or invalid model
}
如何阻止错误重定向?
问题在于,在请求生命周期的后期,FormsAuth模块检查以查看Response.StatusCode
是否为401,如果是,则重定向到登录页面。
您可以尝试使用其他状态代码(例如403,因为这不太适合您的情况)。 另一个选择是延迟将Response.StatusCode
设置为401,直到Global.asax中的EndRequest
事件为止。
我通过在Context.Items
添加一个标志并检查EndRequest
标志的存在来解决此问题:
Global.asax.cs-添加此方法
protected void Application_EndRequest(Object sender, EventArgs e)
{
if(Context.Items["AjaxPermissionDenied"] is bool) // FormsAuth module intercepts 401 response codes and does a redirect to the login page.
{
Context.Response.StatusCode = 401;
Context.Response.StatusDescription = "Permission Denied";
Context.Response.End();
return;
}
}
在您的控制器中
[HttpPost]
[AllowAnonymous]
public JsonResult ApiLogIn(LoginModel model)
{
if (ModelState.IsValid)
{
var outcome = _authService.LogIn(model);
if (outcome == LogInOutcome.Success)
{
return Json(new { }); // Empty on success
}
else
{
Context.Items["AjaxPermissionDenied"] = true;
return Json(new { reason = outcome.ToString() });
}
}
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { }); // Empty or invalid model
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.