1

我们正在使用“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 );
        });

    }

非常感谢任何帮助,在此先感谢。

4

1 回答 1

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);
于 2012-10-08T07:14:41.503 回答