gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:10:11 25 4
gpt4 key购买 nike

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

我如何获得自定义错误消息,它由 CreateErrorResponse()HttpError 参数创建,由 jQuery 的 deferred.fail() 显示>?

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

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

这是一个精简的客户端,它试图找到要显示的错误消息,“午餐失败。”。

$.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);
});

将显示的是:

"error: Internal Server Error: {full stack here}"

我想要的是:

"Failure to lunch."

最佳答案

您可以解析 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');
}
});

关于c# - 如何从 Web Api 获取自定义错误消息到 jQuery.ajax?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18252487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com