gpt4 book ai didi

c# - JQuery ajax 调用在 200 上执行错误

转载 作者:可可西里 更新时间:2023-11-01 08:56:29 25 4
gpt4 key购买 nike

<分区>

我的 c#/WebApi 服务器代码如下所示:

[HttpPost]
public HttpResponseMessage Logout()
{
// do some stuff here ...
return Request.CreateResponse(HttpStatusCode.OK);
}

在客户端中,我使用 jquery 2.0.3 执行 ajax 调用

添加:Jquery 代码( typescript )...

    var ajaxSettings: JQueryAjaxSettings = {};
ajaxSettings.type = 'POST';
ajaxSettings.data = null;
ajaxSettings.contentType = "application/json; charset=utf-8";
ajaxSettings.dataType = "json";
ajaxSettings.processData = false;

ajaxSettings.success = (data: any, textStatus: string, jqXHR: JQueryXHR) => {
console.log("Success: textStatus:" + textStatus + ", status= " + jqXHR.status);
};
ajaxSettings.error = (jqXHR: JQueryXHR, textStatus: string, errorThrow: string) => {
console.log("Error: textStatus:" + textStatus + ", errorThrow = " + errorThrow);
};

$.ajax("http://apidev.someurl.com/v1/users/logout", ajaxSettings);

添加 2:由上述代码生成的请求 header :

POST http://apidev.someurl.com/v1/users/logout HTTP/1.1
Host: apidev.someurl.com
Connection: keep-alive
Content-Length: 0
Cache-Control: no-cache
Pragma: no-cache
Origin: http://apidev.someurl.com
Authorization: SimpleToken 74D06A21-540A-4F31-A9D4-8F2387313998
X-Requested-With: XMLHttpRequest
Content-Type: application/json; charset=utf-8
Accept: application/json, text/javascript, */*; q=0.01
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Referer: http://apidev.someurl.com/test/runner/apitest/index.html?
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

响应为 200,但来自 ajax 调用的错误处理程序被触发,而不是成功处理程序。原因:解析错误,输入意外结束。

一种解决方案是将服务器端代码更改为:

return Request.CreateResponse<String>(HttpStatusCode.OK, "Logout ok");

我知道空响应不是有效的 JSON,但响应消息是故意为空的。 200 说明了一切。响应 header 如下所示:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/7.5
Access-Control-Allow-Origin: http://apidev.someurl.com
Access-Control-Allow-Credentials: true
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 05 Jan 2014 01:20:30 GMT
Content-Length: 0

这是 jquery 中的错误吗?或者 Request.CreateResponse(OK) 永远不应该那样使用吗?我应该在客户端中使用一些解决方法来解决这个问题吗? AFAIK 服务器在这里没有做错......有什么想法吗?

编辑:感谢 kevin、nick 和 John 的反馈,这个问题已经很清楚了。我选择的解决方案是返回一个NoContent

return Request.CreateResponse(HttpStatusCode.NoContent);

对于这种情况,服务器端这似乎是正确的代码。客户端这由 JQuery 完美处理(调用成功处理程序)。感谢大家解决这个问题!

(我不知道该把答案归功于谁......自从nick和kevin在评论中给出了宝贵的反馈,johns的反馈也增加了更好的理解)......如果没有其他建议......我稍后会将唯一的“答案”标记为答案)

谢谢大家!

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