MVC4 - 显示有关错误的更多信息

时间:2012-10-07 19:56:50

标签: asp.net-mvc asp.net-mvc-4

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

    }

任何帮助都非常感谢,提前感谢。

1 个答案:

答案 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);