【问题标题】:How can I set the contentType of a jQuery ajax post so that ASP.NET MVC can read it?如何设置 jQuery ajax 帖子的 contentType 以便 ASP.NET MVC 可以读取它?
【发布时间】:2010-02-04 20:16:44
【问题描述】:

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

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

澄清

我试图实现的目标是将异常消息传递回 ajax 错误事件。目前,即使绕过了 IF 块,错误事件也会正确地引发警告框,但消息是“未找到”。

如您所见,我正在尝试将异常消息设置为 Response.StatusDescription,我相信 ajax 错误中的 xhr.statusText 已设置为。

【问题讨论】:

    标签: jquery asp.net-mvc ajax


    【解决方案1】:

    根据这篇文章:http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/“当没有包含数据时,jQuery没有正确设置指定的content-type。”

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

    【讨论】:

    • 这在 jQuery 1.4 中发生了变化,现在它总是发送内容类型...重要提示:) api.jquery.com/jQuery.ajax
    • 我测试了这个方法,它确实有效。我们在这里使用 jQuery 1.3.2。根据尼克的描述,听起来我在问题中的代码应该适用于 1.4。
    • 这是正确答案。在 beforeSend 中修改 XHR 对象的 content-type 设置在某些浏览器中无法正常工作,服务将返回 XML 而不是 JSON。
    • 我看的越多,我就越同意这是更正确的答案。从其他人同意的赞成票来看。我将更改所选答案。
    【解决方案2】:

    要在 XmlHTTPRequest 中设置自定义标头,您需要利用 jQuery AJAX 调用中的 beforeSend() 选项函数。使用该函数设置额外的标题,如 jQuery API documenation 中所述。

    例子:

      $.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);
        }
      });
    

    【讨论】:

      【解决方案3】:

      将其用作默认内容类型。

      $.ajaxSetup({ contentType: "应用程序/json; charset=utf-8", });

      【讨论】:

        【解决方案4】:

        如果您总是为 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;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-23
          • 2010-12-04
          • 2014-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-03
          • 1970-01-01
          相关资源
          最近更新 更多