9

我有一个奇怪的情况,我的 jquery.post 返回代码 #200(OK),但错误处理程序被命中。

这是我的 MVC WebAPI 服务器端代码(它所做的只是返回代码 #200 OK):

[HttpPost]
public HttpResponseMessage Post(T input)
{
    //_handler.Create(input);

    return Request.CreateResponse(HttpStatusCode.OK);
}

这是我的客户端脚本

ServerAccess.prototype.Save = function (m) {

            $.post("http://localhost:55482/M/", m)
            .success(
                function (o) {
                    alert("success");
                })
            .error(
                function (xhr, textStatus, errorThrown) {
                    if (typeof console == 'object' && typeof console.log == 'function') {
                        console.log(xhr);
                        console.log(textStatus);
                        console.log(errorThrown);
                    }
                }
            );
        };

Firebug 中的控制台输出为:

POST http://localhost:55482/M/ 200 OK 894 毫秒

标头


响应标头

内容长度 6

内容类型应用程序/json;字符集=utf-8

日期 2012 年 10 月 28 日星期日 18:55:17 GMT

服务器 Microsoft-HTTPAPI/2.0


请求标头

接受 /

接受编码 gzip,放气

接受语言 nb-no,nb;q=0.9,no-no;q=0.8,no;q=0.6,nn-no;q=0.5,nn;q=0.4,en-us;q=0.3,en ;q=0.1

连接保持活动

内容长度 21

内容类型应用程序/x-www-form-urlencoded;字符集=UTF-8

主机本地主机:55482

原点空

用户代理 Mozilla/5.0 (Windows NT 6.2; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0

对象 { readyState=0, status=0, statusText="error"}

错误

(一个空字符串)

我四处浏览并看到其他人也有类似的问题,通常响应中的 JSON 格式不正确。由于我只返回 200 OK 并且没有内容,这似乎不适合我的情况。但是我确实尝试像这样返回一个空对象

var o = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(new T());

return Request.CreateResponse(HttpStatusCode.OK, o);

服务器端从 Visual Studio 2012 运行,客户端只是一个带有一些 .js 文件的独立 .html。此外,在 VS 中有一个断点,我知道服务器收到了请求,并且使用 Postman for Chrome 一切都很好。

所以问题当然是:我在这里做错了什么?为什么错误处理程序会被命中?

谢谢!

4

4 回答 4

3

试试这个:

ServerAccess.prototype.Save = function (m) {
    $.ajax({
        "type": "POST",
        "url": "http://localhost:55482/M/",
        "data": m,
        "dataType": "json",
        "success": function (data, textStatus, xhr) {
            alert("success");
        },
        "error": function (xhr, textStatus, errorThrown) {
            if (typeof console === 'object' && typeof console.log === 'function') {
                console.log(xhr);
                console.log(textStatus);
                console.log(errorThrown);
            }
        }
    });
};

这允许您设置预期的返回 MIME 类型application/json

更新

如果您在 上运行独立的 HTML 页面http://localhost:55482,则它不会是跨域的。如果您在file:///C:/Users/.../Desktop/test.htm其他地方或其他地方运行它,那么它将是一个跨域请求。httpvshttps:也有所作为。

jsonp请求是请求,GET不能是POST. 这是因为jsonp请求是通过向<script>页面添加一个元素来实现的,其中源设置为您的 url,data并附加到查询字符串(加上时间戳参数)。任何POST期望jsonp返回的请求都应自动转换为GET请求。

最后,由于您的例程需要返回数据,因此您需要返回一些实际数据,因为 jQuery 将尝试解析返回到对象中的 JSON(如果没有返回数据,则无法执行此操作)并且如果有数据将抛出错误无法解析。

尝试将您的响应消息更改为:

String o = "success";
System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();

return Request.CreateResponse(HttpStatusCode.OK, ser.Serialize(o));
于 2012-10-28T19:55:18.940 回答
0

据我了解,您需要跨域,因此您应该有一个处理程序或服务调用者

阅读这个它可能对你有用。

在应用程序启动中添加 JsonpFormatter 作为过滤器,然后您就可以享受 jsonp 了。

于 2013-06-03T07:22:20.500 回答
0

这很可能与您发送的空响应有关。请参阅此错误报告:http ://aspnetwebstack.codeplex.com/workitem/1664

您可以通过将空字符串设置为响应来解决此问题。

return Request.CreateResponse(HttpStatusCode.OK, "");

该错误报告包含一个解决方法,其中涉及创建一个消息处理程序,该处理程序在 content == null 的位置添加一个空字符串。

public class HttpResponseMessageHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {


            var response = await base.SendAsync(request, cancellationToken);

            if (response.Content == null && request.Headers.Accept.Any(a => a.MediaType == "application/json"))
            {
                var content = new StringContent("{}");
                content.Headers.ContentLength = 2;
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                response.Content = content;
            }

            return response;
        }
    }
于 2014-06-25T14:14:21.027 回答
0

我刚刚在对 WebApi 2 服务使用 JSON 请求时遇到了这个问题。对我来说,只需更改成功和错误函数的参数列表即可解决(WebApi 端无需更改)

我从这里更改了我的代码

success: function (data) { alert(data); },
error: function (error) { jsonValue = jQuery.parseJSON(error.responseText); }

对此

success: function (data, textStatus, xhr) 
{ 
  alert("data: " + data + "\ntextStatus: " + textStatus + "\nxhr: " + xhr);
},
error: function (xhr, textStatus, errorThrown)
{                       
  alert("xhr: " + xhr + "\ntextStatus: " + textStatus + "\nerrorThrown " + errorThrown);
}

注意参数列表的变化

于 2015-07-20T09:35:20.777 回答