[英]How to get a custom error message from Web Api to jQuery.ajax?
This code uses the Microsoft Web Api Http stack and jQuery. 此代码使用Microsoft Web Api Http堆栈和jQuery。
How do I get a custom error message, created by an HttpError parameter to CreateErrorResponse() , displayed by jQuery's deferred.fail() ? 如何获取由jQuery的deferred.fail()显示的,由CreateErrorResponse()的HttpError参数创建的自定义错误消息?
An example of creating an error response for test purposes in an ApiController: 在ApiController中为测试目的创建错误响应的示例:
public HttpResponseMessage Post(Region region)
{
var error = new HttpError("Failure to lunch.");
return this.Request.CreateErrorResponse(
HttpStatusCode.InternalServerError,
error);
}
Here's a cut-down client that's trying to find the error message to display, "Failure to lunch.". 这是一个简化的客户端,试图查找显示“失败午餐”的错误消息。
$.ajax({
type: 'POST',
url: 'api/region',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(region)
})
.fail(function (jqXhr, textStatus, errorThrown) {
alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText);
});
What will be displayed is: 将显示的内容是:
"error: Internal Server Error: {full stack here}" “错误:内部服务器错误:{此处是完整堆栈}”
What I want instead is: 我想要的是:
"Failure to lunch." “午餐失败。”
You could parse the responseText
string and then use the Message
property: 您可以解析responseText
字符串,然后使用Message
属性:
.fail(function (jqXhr, textStatus, errorThrown) {
if (jqXhr.getResponseHeader('Content-Type').indexOf('application/json') > -1) {
// only parse the response if you know it is JSON
var error = $.parseJSON(jqXhr.responseText);
alert(error.Message);
} else {
alert('Fatal error');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.