doq*_*que 8 rest error-handling asp.net-web-api
有没有办法更改Web Api的错误消息的默认行为,例如:
GET /trips/abc
Run Code Online (Sandbox Code Playgroud)
回复(转述):
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."
}
Run Code Online (Sandbox Code Playgroud)
我想避免给出关于我的代码的这些相当详细的信息,而是用以下代码替换它:
HTTP 500 Bad Request
{
error: true,
error_message: "invalid parameter"
}
Run Code Online (Sandbox Code Playgroud)
我可以在UserController中执行此操作,但代码执行甚至没有那么远.
编辑:
我已经找到了一种从输出中删除详细错误消息的方法,使用Global.asax.cs中的这行代码:
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy =
IncludeErrorDetailPolicy.LocalOnly;
Run Code Online (Sandbox Code Playgroud)
这会产生如下消息:
{
"Message": "The request is invalid."
}
Run Code Online (Sandbox Code Playgroud)
哪个更好,但不完全是我想要的 - 我们已经指定了许多数字错误代码,这些代码被映射到客户端的详细错误消息.我想只输出相应的错误代码(我可以在输出之前选择,最好通过查看发生了什么样的异常),例如:
{ error: true, error_code: 51 }
Run Code Online (Sandbox Code Playgroud)
You might want to keep the shape of the data as the type HttpError even if you want to hide detailed information about the actual exception. To do that, you can add a custom DelegatingHandler to modify the HttpError that your service throws.
Here is a sample of how the DelegatingHandler might look like:
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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3346 次 |
| 最近记录: |