如何设置 jQuery ajax 帖子的 contentType 以便 ASP.NET MVC 可以读取它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2202857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set the contentType of a jQuery ajax post so that ASP.NET MVC can read it?
提问by Sailing Judo
I have some jQuery that looks like this:
我有一些看起来像这样的 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);
}
});
If the action being called causes an exception it will ultimately get picked up by the Global.asax Application_Error where I have some code like this:
如果被调用的操作导致异常,它最终会被 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 ...
}
When I execute the script that does the post the Request.ContentType is always an empty string and therefore does not hit the first if block. Is there some other value that I should be putting in the ajax "contentType"? Or is there another way for me to tell asp.net that the content type should be "application/json"?
当我执行执行 post 的脚本时,Request.ContentType 总是一个空字符串,因此不会命中第一个 if 块。我应该在ajax“contentType”中放入其他一些值吗?或者我是否有另一种方式告诉 asp.net 内容类型应该是“application/json”?
Clarification
澄清
The goal I am trying to achieve is to pass the exception message back to the ajax error event. Currently, even though the IF block is being bypassed, the error event correctly throws an alert box but the message is "Not Found".
我试图实现的目标是将异常消息传递回 ajax 错误事件。目前,即使绕过 IF 块,错误事件也会正确地抛出一个警告框,但消息是“未找到”。
As you can see I am trying to set the exeception message to the Response.StatusDescription which I believe the xhr.statusText in the ajax error is set to.
如您所见,我正在尝试将异常消息设置为 Response.StatusDescription,我相信 ajax 错误中的 xhr.statusText 设置为。
回答by typeoneerror
Accordiing to this article: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/"jQuery does not properly set the specified content-type when there is no data included. "
根据这篇文章: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"
});
回答by Michael Bray
To set custom headers in the XmlHTTPRequest, you need to utilize the beforeSend() option function in the jQuery AJAX Call. Use that function to set additional headers, as described in the jQuery API documenation.
要在 XmlHTTPRequest 中设置自定义标头,您需要利用 jQuery AJAX 调用中的 beforeSend() 选项函数。使用该函数来设置其他标头,如jQuery API 文档中所述。
Example:
例子:
$.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);
}
});
回答by Keith Rousseau
If you are always returning json for Ajax errors, then you can just use the following to detect that it is an Ajax call:
如果您总是为 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;
回答by varun
Use this to default content type.
使用它来默认内容类型。
$.ajaxSetup({ contentType: "application/json; charset=utf-8", });
$.ajaxSetup({ contentType: "application/json; charset=utf-8", });