rest – 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 }

解决方法

您可能希望将数据的形状保持为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;
        });
    }
}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...