asp.net Web Api - 默认错误消息

时间:2012-10-22 14:48:43

标签: rest error-handling asp.net-web-api

是否有办法更改Web Api的错误消息的默认行为,例如:

GET /trips/abc

回复(转述):

HTTP 500 Bad Request

{
    "Message": "The request is invalid.",
    "MessageDetail": "The parameters dictionary contains a null entry for parameter 'tripId' of non-nullable type 'System.Guid' for method 'System.Net.Http.HttpResponseMessage GetTrip(System.Guid)' in 'Controllers.TripController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}

我想避免提供有关我的代码的相关详细信息,而是用以下内容替换它:

HTTP 500 Bad Request
{
    error: true,
    error_message: "invalid parameter"
}

我可以在UserController中执行此操作,但代码执行甚至没有那么远。

编辑:

我找到了一种从输出中删除详细错误消息的方法,使用Global.asax.cs中的这行代码:

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy =
IncludeErrorDetailPolicy.LocalOnly;

这会产生如下消息:

{
    "Message": "The request is invalid."
}

哪个更好,但不完全是我想要的 - 我们已经指定了许多数字错误代码,这些代码映射到客户端的详细错误消息。我想只输出相应的错误代码(我可以在输出之前选择,最好是看看发生了什么样的异常),例如:

{ error: true, error_code: 51 }

2 个答案:

答案 0 :(得分:8)

即使您想要隐藏有关实际异常的详细信息,您也可能希望将数据的形状保持为HttpError类型。为此,您可以添加自定义DelegatingHandler来修改服务引发的HttpError。

以下是DelegatingHandler的示例:

public class CustomModifyingErrorMessageDelegatingHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) =>
        {
            HttpResponseMessage response = responseToCompleteTask.Result;

            HttpError error = null;
            if (response.TryGetContentValue<HttpError>(out error))
            {
                error.Message = "Your Customized Error Message";
                // etc...
            }

            return response;
        });
    }
}

答案 1 :(得分:2)

Maggie的回答对我也有用。谢谢发帖!

只是想在她的代码中添加一些内容以获得更多说明:

HttpResponseMessage response = responseToCompleteTask.Result;
HttpError error = null;

if ((!response.IsSuccessStatusCode) && (response.TryGetContentValue(out error)))
{
    // Build new custom from underlying HttpError object.
    var errorResp = new MyErrorResponse();

    // Replace outgoing response's content with our custom response
    // while keeping the requested MediaType [formatter].
    var content = (ObjectContent)response.Content;
    response.Content = new ObjectContent(typeof (MyErrorResponse), errorResp, content.Formatter);
}

return response;

其中:

   public class MyErrorResponse
   {
       public MyErrorResponse()
       { 
          Error = true; 
          Code = 0; 
       }

       public bool Error { get; set; }
       public int Code { get; set; }
   }