我怎样才能设置一个jQuery AJAX职位的contentType使ASP.NET MVC可以看了吗?
我有一些jQuery,看起来像这样:
I have some jQuery that looks like this:
$.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在那里我有一些code是这样的:
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:
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始终是一个空字符串,因此不撞头,如果块中的脚本。有,我应该把在AJAX的contentType一些其他的价值?还是有另一种办法,我要告诉asp.net的内容类型应该是应用程序/ JSON?
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"?
澄清
我想达到的目标是通过异常消息回到阿贾克斯错误事件。目前,尽管IF块被旁路时,错误事件正确地抛出一个警告框,但消息是未找到。
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".
正如你可以看到我试图设置exeception消息Response.StatusDescription我相信xhr.statusText在Ajax错误设置。
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.
Accordiing这篇文章:http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ jQuery的不正确设置指定的内容类型时,有没有包含数据。
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. "
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/WebMethodName",
data: "{}",
dataType: "json"
});