rest – asp.net Web Api – 默认错误消息
发布时间:2020-05-24 10:30:53 所属栏目:asp.Net 来源:互联网
导读:有没有办法更改Web Api的错误消息的默认行为,例如: GET /trips/abc 回应(转述): HTTP 500 Bad Request{ Message: The request is invalid., MessageDetail: The parameters dictionary contains a null entry for paramete
|
有没有办法更改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;
});
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 使用Asp.Net Identity 2在AspNetUserClaims中存储用户信息有
- asp.net – MSBuild:自动收集db迁移脚本?
- asp-classic – 与SQL Server Compact Edition 4.0的Ado连接
- asp.net – 当用户按下文本框中的返回时,我可以取消回发吗?
- asp.net单选按钮分组
- ASP.NET Forms Authentication阻止在Login.aspx上加载javas
- asp.net – 当通过文件上传控件上传文件时,在c#.net中重命名
- asp.net – 静态方法的缺点是什么?
- asp.net-mvc-3 – 具有MVC属性的IoC / DI
- asp.net-mvc – 如何下载Razor View引擎
推荐文章
站长推荐
- asp.net – 小数点后尾数为零
- asp.net-web-api – 随着SerilogWeb.Owin停产,是
- asp.net-mvc – ASP.NET MVC 3远程验证允许原始值
- 如何在ASP.NET中的多个Web应用程序中维护相同的会
- asp.net – Signalr中哪个更好的WebSocket或Long
- 阻止拦截ASP.NET Web API响应的FormsAuthenticat
- asp.net-mvc-4 – 捆绑从CDN提供的多个CSS?
- asp.net-mvc – 如何将服务器错误的http状态代码
- asp.net – aspx中的设计视图没有加载
- asp.net-mvc – ASP.NET MVC5/IIS Express无法调
热点阅读
