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

Sai*_*udo 14 ajax asp.net-mvc jquery

我有一些看起来像这样的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);
     }
});
Run Code Online (Sandbox Code Playgroud)

如果被调用的动作导致异常,它最终将被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 ...
}
Run Code Online (Sandbox Code Playgroud)

当我执行发布帖子的脚本时,Request.ContentType始终是一个空字符串,因此不会遇到第一个if块.我应该在ajax"contentType"中添加一些其他值吗?或者我有另一种方式告诉asp.net内容类型应该是"application/json"吗?

澄清

我试图实现的目标是将异常消息传递回ajax错误事件.目前,即使绕过IF块,错误事件也会正确抛出警告框,但消息为"未找到".

正如您所看到的,我正在尝试将exeception消息设置为Response.StatusDescription,我相信ajax错误中的xhr.statusText设置为.

typ*_*ror 22

根据这篇文章:http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ "jQuery在没有时没有正确设置指定的内容类型数据包括在内."

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebService.asmx/WebMethodName",
  data: "{}",
  dataType: "json"
});
Run Code Online (Sandbox Code Playgroud)


Mic*_*ray 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);
    }
  });
Run Code Online (Sandbox Code Playgroud)