如何设置jQuery ajax post的contentType,以便ASP.NET MVC可以读取它?

16

我有一些类似于这样的jQuery代码:

$.ajax({
     type: "POST",
     url: "/Customer/CancelSubscription/<%= Model.Customer.Id %>",
     contentType: "application/json",
     success: refreshTransactions,
     error: function(xhr, ajaxOptions, thrownError) {
         alert("Failed to cancel subscription! Message:" + xhr.statusText);
     }
});
如果调用的操作引发异常,最终将被 Global.asax 中的 Application_Error 捕获,我有一些类似以下代码的处理:
var ex = Server.GetLastError();
if (Request.ContentType.Contains("application/json"))
{
     Response.StatusCode = 500;
     Response.StatusDescription = ex.Message;
     Response.TrySkipIisCustomErrors = true;
}
else
{
     // some other way of handling errors ...
}
当我执行进行帖子的脚本时,Request.ContentType总是空字符串,因此不会触发第一个if块。在ajax的"contentType"中是否应该放置其他值?或者有没有其他方法告诉asp.net内容类型应该是"application/json"?
澄清: 我尝试实现的目标是将异常消息传递回ajax错误事件。目前,即使绕过了IF块,错误事件也会正确地抛出警报框,但消息为“未找到”。
正如您所看到的,我正在尝试将exeception消息设置为Response.StatusDescription,我相信ajax错误中的xhr.statusText被设置为该值。
4个回答

24

1
这在jQuery 1.4中有所改变,现在它总是发送内容类型...重要提示 :) http://api.jquery.com/jQuery.ajax/ - Nick Craver
我测试了这个方法,它确实有效。我们在这里使用的是jQuery 1.3.2版本。从Nick所描述的来看,我的问题中的代码应该可以在1.4版本中工作。 - Sailing Judo
1
这是正确的答案。在beforeSend中修改XHR对象的content-type设置在某些浏览器中无法正常工作,服务将返回XML而不是JSON。 - Dave Ward
我越看越同意这是更正确的答案。从点赞数量来看,其他人也同意。我会改变所选的答案。 - Sailing Judo

6
为了在XmlHTTPRequest中设置自定义头文件,您需要使用jQuery AJAX调用中的beforeSend()选项函数。使用该函数设置其他标题,如 jQuery API文档中所述。
例子:
  $.ajax({
    type: "POST",
    url: "/Customer/CancelSubscription/<%= Model.Customer.Id %>",
    beforeSend: function(xhr) {
      xhr.setRequestHeader( "Content-type", "application/json" );
    },
    success: refreshTransactions,
    error: function(xhr, ajaxOptions, thrownError) {
       alert("Failed to cancel subscription! Message:" + xhr.statusText);
    }
  });

1
使用此选项来设置默认的内容类型。

$.ajaxSetup({ contentType: "application/json; charset=utf-8", });


0

如果您总是返回 Ajax 错误的 JSON,则可以使用以下代码检测它是否为 Ajax 调用:

// jQuery sets a header of 'x-requested-with' in all requests
            string[] ajaxHeader = httpRequest.Headers.GetValues("x-requested-with");
            if (ajaxHeader != null && ajaxHeader.Length > 0)
            {
                return ajaxHeader[0].Equals("XMLHttpRequest", StringComparison.InvariantCultureIgnoreCase);
            }
            return false;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接