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

我有一些看起来像这样的jQuery:

$.ajax({ type: "POST", url: "/Customer/CancelSubscription/", contentType: "application/json", success: refreshTransactions, error: function(xhr, ajaxOptions, thrownError) { alert("Failed to cancel subscription! Message:" + xhr.statusText); } }); 

如果被调用的动作导致exception,它最终将被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 ... } 

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

澄清

我想要实现的目标是将exception消息传递回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" }); 

要在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); } }); 

如果你总是返回json的Ajax错误,那么你可以使用以下内容来检测它是一个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; 

使用此选项可以默认内容类型。

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