问题描述
我试图控制来自Web API 2 OData v4服务的错误响应中详细信息的存在.当我点击本地IIS上托管的OData服务时,会得到如下信息:
I'm trying to control the presence of details in error responses from a Web API 2 OData v4 service. When I hit the OData service hosted on my local IIS, I get something like this:
{
"error": {
"code": "Error code",
"message": "Message from exception filter",
"details": [
{
"code": "Detail code",
"message": "Details here"
}
],
"innererror": {
"message": "Exception message here",
"type": "Exception type",
"stacktrace": "Stack trace here"
}
}
}
当我使用相同的服务并将其部署在远程服务器上,并用相同的消息将其击中时,我得到以下信息:
When I take the same service and deploy it on a remote server, and hit it with the same message, I get this:
{
"error": {
"code": "Error code",
"message": "Message from exception filter"
}
}
我猜想"innererror"和"details"部分被抑制了,因为我正在远程调用该服务?我很高兴"innererror"部分得到了抑制-我不想泄漏那些细节-但我想公开"details"部分,以便针对某些错误提供更多反馈.有没有简单的方法可以做到这一点?
I'm guessing that the "innererror" and "details" sections are suppressed because I'm calling the service remotely? I'm happy that the "innererror" section is suppressed - I don't want to leak those details - but I want to expose the "details" section so that I can provide some more feedback on certain errors. Is there a simple way to achieve this?
谢谢!
推荐答案
我正在使用 Request.CreateErrorResponse(myHttpStatusCode,myODataError)创建OData错误响应.查看System.Web.Http.OData.Extensions.HttpRequestMessageExtensions.CreateErrorResponse的源代码,似乎如果Request.ShouldIncludeErrorDetail为false,则仅使用代码"和消息"项重新创建ODataError.我的解决方案是创建CreateErrorResponse的另一个重载/扩展,该重载/扩展接受一个参数,该参数控制是否应包含详细信息部分:
I was creating my OData error responses using Request.CreateErrorResponse(myHttpStatusCode, myODataError). Looking at the source code of System.Web.Http.OData.Extensions.HttpRequestMessageExtensions.CreateErrorResponse, it appears that if Request.ShouldIncludeErrorDetail is false, then the ODataError is recreated with just the "code" and "message" items. My solution was to create another overload/extension of CreateErrorResponse which accepts a parameter that controls whether the details section should be included:
public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage request,
HttpStatusCode statusCode, ODataError oDataError, bool includeDetails)
{
if (request.ShouldIncludeErrorDetail())
{
return request.CreateResponse(statusCode, oDataError);
}
else
{
return request.CreateResponse(
statusCode,
new ODataError()
{
ErrorCode = oDataError.ErrorCode,
Message = oDataError.Message,
Details = includeDetails ? oDataError.Details : null
});
}
}
这可以独立于详细信息"部分而抑制内部错误"部分.
This allows the "innererror" section to be suppressed independently of the "details" section.
这篇关于如何控制OData错误详细信息的存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!