代码之家  ›  专栏  ›  技术社区  ›  Sailing Judo

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

  •  13
  • Sailing Judo  · 技术社区  · 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应用程序\错误捕获,其中我有如下代码:

    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块,错误事件也会正确地抛出一个警告框,但消息是“未找到”。

    如您所见,我正在尝试将exeception消息设置为response.statusDescription,我认为Ajax错误中的xhr.statusText设置为。

    4 回复  |  直到 10 年前
        1
  •  19
  •   typeoneerror    16 年前

    根据本条: 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"
    });
    
        2
  •  6
  •   Michael Bray    16 年前

    要在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
  •  0
  •   Keith Rousseau    16 年前

    如果总是返回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;
    
        4
  •  0
  •   varun    10 年前

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

    $AjAxStutter({ contenttype:“application/json;charset=utf-8”, (});