我的c#/ WebApi服务器代码看起来像:
[HttpPost] public HttpResponseMessage logout() { // do some stuff here ... return Request.CreateResponse(HttpStatusCode.OK); }
在客户端,我使用jquery 2.0.3做一个ajax调用
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,errorThrow: string) => { console.log("Error: textStatus:" + textStatus + ",errorThrow = " + errorThrow); }; $.ajax("http://apidev.someurl.com/v1/users/logout",ajaxSettings);
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调用的错误处理程序被触发,而不是成功处理程序.原因:parseerror,意外的输入结束.
return Request.CreateResponse<String>(HttpStatusCode.OK,"logout ok");
我了解一个空的响应是无效的JSON,但响应消息是有意的空. 200说这一切.
响应标题如下所示:
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);
ServeRSSide这个案例似乎是正确的代码.客户端这完全由JQuery处理(调用了succes处理程序). Thanx全部清除了!
(我不知道谁给信用的答案…因为nick和kevin在评论中给了他们宝贵的反馈,约翰的反馈也增加了一个更好的理解)…如果没有其他建议…我会后来标记唯一的“答案”作为答案)
感谢所有!
解决方法
Equivalent to HTTP status 200. OK indicates that the request succeeded and that the requested information is in the response. This is the most common status code to receive.
因为200意味着一些内容是与响应一起发送的(即使一个空的JSON对象字面值也会很好),如果jQuery的Ajax实现假定一个非零长度的响应,但是没有收到它,特别是如果它尝试解析JSON(也可能是XML).这就是为什么John S提出将dataType改为text的建议;这样做可以让您在接收到空的响应时采取具体的操作.
另一方面,HttpStatusCode.NoContent被定义为(强调我的):
Equivalent to HTTP status 204. NoContent indicates that the request has been successfully processed and that the response is intentionally blank.
在您的特定情况下,将状态代码设置为HttpStatusCode.NoContent可能更有意义,以确保jQuery Ajax了解其不需要尝试任何解析/处理响应.