C# 如何从Web Api到jQuery.ajax获取自定义错误消息?
此代码使用MicrosoftWebAPI Http堆栈和jQuery 如何获取由HttpError参数创建的自定义错误消息,该消息由jQuery的deferred.fail()显示在CreateErrorResponse()中 在ApicController中为测试目的创建错误响应的示例:C# 如何从Web Api到jQuery.ajax获取自定义错误消息?,c#,jquery,asp.net-web-api,httpresponse,jqxhr,C#,Jquery,Asp.net Web Api,Httpresponse,Jqxhr,此代码使用MicrosoftWebAPI Http堆栈和jQuery 如何获取由HttpError参数创建的自定义错误消息,该消息由jQuery的deferred.fail()显示在CreateErrorResponse()中 在ApicController中为测试目的创建错误响应的示例: public HttpResponseMessage Post(Region region) { var error = new HttpError("Failure to lunch.");
public HttpResponseMessage Post(Region region)
{
var error = new HttpError("Failure to lunch.");
return this.Request.CreateErrorResponse(
HttpStatusCode.InternalServerError,
error);
}
这是一个精简的客户端,它试图找到要显示的错误消息“午餐失败”
将显示的内容是:
“错误:内部服务器错误:{full stack here}”
我想要的是:
“没吃午饭。”
您可以分析
responseText
字符串,然后使用消息
属性:
.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');
}
});
你是说“发射失败”不是吗lunch@KevinHolditch我饿了!我现在也是。我读了你的问题:)这就是我感到困惑的地方。jqXhr.responseText.Message包含来自InternalServerError的错误消息(“发生了错误”),而不是我放入HttpError的自定义消息。我在回答中出错。您应该使用
alert(error.Message)
而不是alert(error.Message)
。Message属性将包含文本午餐失败。
。我刚刚测试过,效果很好。你能显示jqXhr.responseText
的值吗?我很困惑,因为我的测试用例抛出了另一个InternalServerError异常,它是在我的CreateErrorResponse代码被命中之前返回的。Web API将在没有任何try..catch代码的情况下轻松处理此问题。你说得很对,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');
}
});