gpt4 book ai didi

javascript - MVC AJAX 请求返回不正确的状态代码

转载 作者:行者123 更新时间:2023-11-30 20:42:53 26 4
gpt4 key购买 nike

我正在提交一个标准 $.ajax()像这样请求:

$.ajax({
type: "GET",
url: myUrl
success: function(data) {
$("#replace").html(data)
},
error: function (data) {
console.warn(data);
}
});

或者通过将处理程序附加到 ajax promise 同样的事情像这样的回调:

$.ajax({
type: "GET",
url: myUrl
})
.done(function(data, status) {
console.log(data);
})
.fail(function(data, status) {
console.warn(status);
});

在这两种情况下,或使用 $.ajaxError() handler 时,当返回 HTTP 状态错误时调用 error/fail 函数。


在我的 ASP.NET MVC 项目中,我试图返回正确的 HTTP 状态代码,这既是出于语义原因,也是为了被正确的客户端处理程序捕获。

尝试 #1 - 根据 this answer 的建议我试图返回 HttpStatusCodeResult像这样:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Unauthorized, accessResult.AccessDeniedMessage);
filterContext.HttpContext.Response.End();
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}

尝试 #2 - 或者,按照 this answer 的建议,我尝试返回一个 JsonResult 并设置 Response.StatusCode

filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
filterContext.Result = new JsonResult()
{
Data = new { Error = "Unauthorized User" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.End();

在这两种情况下,响应仍然返回为 200 OK

AJAX Status Code Screenshot

问题:

  • 我应该返回带有未授权状态代码的 AJAX 响应的语义是否正确?
  • 还有其他地方可以设置我需要做的这个值吗?
  • 是否有某些服务器级别设置允许返回非 200 状态代码?

关于 Always success on ajax post with HttpResponseMessage 401 的问题似乎遇到了同样的错误,但没有提出服务器端解决方案,而是只允许 OK 错误状态代码并抓取响应以确定是否发生错误。

最佳答案

违规问题确实与 Always success on ajax post with HttpResponseMessage 401 中的问题相同.成功返回响应,但陷入重定向到表单登录

<b>X-Responded-JSON</b>: {"status": 401, "headers": {"location":"http:\/\/localhost:50004\/Login?ReturnUrl=%2FClient"}}

虽然这个问题似乎并没有暗示服务器端的解决方案,而是简单地依赖于在客户端解析错误状态。 Brock Allen 在他关于 Using cookie authentication middleware with Web API and 401 response codes 的帖子中建议服务器端修复:

Normally when using cookie authentication middleware, when the server (MVC or WebForms) issues a 401, then the response is converted to a 302 redirect to the login page (as configured by the LoginPath on the CookieAuthenticationOptions). But when an Ajax call is made and the response is a 401, it would not make sense to return a 302 redirect to the login page. Instead you’d just expect the 401 response to be returned. Unfortunately this is not the behavior we get with the cookie middleware — the response is changed to a 200 status code with a JSON response body with a message:

{"Message":"Authorization has been denied for this request."}

I’m not sure what the requirement was for this feature. To alter it, you must take over control of the behavior when there is a 401 unauthorized response by configuring a CookieAuthenticationProvider on the cookie authentication middleware:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnApplyRedirect = ctx =>
{
if (!IsAjaxRequest(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
}
});

Notice it handles the OnApplyRedirect event. When the call is not an Ajax call, we redirect. Otherwise, we do nothing which allows the 401 to be returned to the caller.

The check for IsAjaxRequest is simply copied from a helper in the katana project:

private static bool IsAjaxRequest(IOwinRequest request)
{
IReadableStringCollection query = request.Query;
if ((query != null) && (query["X-Requested-With"] == "XMLHttpRequest"))
{
return true;
}
IHeaderDictionary headers = request.Headers;
return ((headers != null) && (headers["X-Requested-With"] == "XMLHttpRequest"));
}

关于javascript - MVC AJAX 请求返回不正确的状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49054085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com