c# - Web api dotnet 核心中 Api 版本控制错误的自定义错误响应

标签 c# error-handling .net-core custom-error-handling api-versioning

我正在为 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/

相关文章:

c# - Access 更新语句在 C# 中不起作用

c# - 如何列出网络计算机上的所有打印机

error-handling - 快速错误处理: scope

c# - System.Reflection.AmbiguousMatchException : 'Ambiguous match found.'

azure - 从 octopus 部署到 azure 出现连接错误

c# - 更改绑定(bind)属性时,ListView 分组不会更新

c# - 如何在应用程序启动时获取请求 URL

python - Tweepy 在 search_recent_tweets <> 上出现 401 错误,但在 create_tweet 时没有出现 401 错误?

c++11 - 可选抛出constexpr吗?

Azure Servicebus 队列接收有序消息时的延迟