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

我有一些看起来像这样的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设置为.

解决方法

根据这篇文章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"
});

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...