我们正在使用“HttpResponseExpection”来抛出异常消息。异常时,尝试显示错误内容和ReasonPhrase,但它只显示错误状态代码。 发布了我用于显示消息的代码。
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No Product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found",
StatusCode = HttpStatusCode.Forbidden
}; throw new HttpResponseException(resp);
index.cshtml中的代码
function find() {
clearStatus();
var id = $('#productId').val();
$.getJSON(API_URL + id,
function (data) {
viewModel.Name(data.Name);
viewModel.Category(data.Category);
viewModel.Price(data.Price);
})
.fail(
function (jqXHR, textStatus, err) {
$('#status').html('Error: ' + err );
});
}
任何帮助都非常感谢,提前感谢。
答案 0 :(得分:1)
responseText
对象的jqXHR
属性将包含错误消息(Content
属性):
.fail(function (jqXHR, textStatus, err) {
alert(jqXHR.responseText);
});
如果您想获取ReasonPhrase
属性,请使用err
参数:
.fail(function (jqXHR, textStatus, err) {
alert(err);
});
还要确保在API控制器上使用正确的状态代码404(HttpStatusCode.NotFound
)而不是403(HttpStatusCode.Forbidden
):
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No Product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found",
StatusCode = HttpStatusCode.Forbidden
};
throw new HttpResponseException(resp);