我正在为 Webapi 服务中的所有错误创建一个包库。该库将用于为 BadRequest、BadArgument、ApiVersionsing 等相关错误提供自定义响应。我需要帮助自定义与 Apiversion 相关的错误 - ApiVersionUnspecified、UnsupportedApiVersion、InvalidApiVersion、AmbiguousApiVersion。我已按照本文为我的项目添加 api 版本控制 - https://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx
我已经检查了上述包的 github wiki,发现“根据所需的行为,您可以扩展 DefaultErrorResponseProvider 或者您可以从 stratch 实现您自己的 IErrorResponseProvider。
要设置备用错误响应行为,请将默认提供程序替换为您自己的:“
options => options.ErrorResponses = new MyErrorResponseProvider();
但是;我不太明白如何在 MyErrorResponseProvider 类中自定义默认错误响应。有人可以给我提供任何示例,以便我开始使用吗?
提前致谢!
最佳答案
找到上面的实现方式为-
class MyErrorResponseProvider : DefaultErrorResponseProvider
{
// note: in Web API the response type is HttpResponseMessage
public override IActionResult CreateResponse( ErrorResponseContext context )
{
switch ( context.ErrorCode )
{
case "UnsupportedApiVersion":
context = new ErrorResponseContext(
context.Request,
context.StatusCode,
context.ErrorCode,
"My custom error message.",
context.MessageDetail );
break;
}
return base.CreateResponse( context );
}
}
感谢 github issue @ - https://github.com/Microsoft/aspnet-api-versioning/issues/233
关于c# - Web api dotnet 核心中 Api 版本控制错误的自定义错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49124472/