如何从Web Api获取自定义错误消息到jQuery.ajax?

Bog*_*gin 10 c# jquery httpresponse jqxhr asp.net-web-api

此代码使用Microsoft Web Api Http堆栈和jQuery.

如何获取由jQuery的deferred.fail()显示的由HttpError参数创建的自定义错误消息给CreateErrorResponse ()

在ApiController中为测试目的创建错误响应的示例:

public HttpResponseMessage Post(Region region)
{
    var error = new HttpError("Failure to lunch.");
    return this.Request.CreateErrorResponse(
               HttpStatusCode.InternalServerError, 
               error);
}
Run Code Online (Sandbox Code Playgroud)

这是一个减少客户端,试图找到要显示的错误消息,"未能午餐.".

$.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);
});
Run Code Online (Sandbox Code Playgroud)

将显示的是:

"错误:内部服务器错误:{full stack here}"

我想要的是:

"没有吃午饭."

Dar*_*rov 8

您可以解析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');
    }
});
Run Code Online (Sandbox Code Playgroud)