Customized error responses for ApiVersioning errors in webapi dotnet core

北城以北 提交于 2019-12-13 16:22:57

问题


I am creating a package lib for all the errors in a Webapi service. This library will be used for providing custom responses for BadRequest, BadArgument, ApiVersionsing etc.. related errors. I need help in customizing Apiversion related errors for - ApiVersionUnspecified, UnsupportedApiVersion, InvalidApiVersion, AmbiguousApiVersion. I have follow this article to include api-versioning for my project - https://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx

I have checked the github wiki for the above package and found that "Depending on the desired behavior, you can extend the DefaultErrorResponseProvider or you can implement your own IErrorResponseProvider from stratch.

To wire up an alternate error response behavior, replace the default provider with your own:"

options => options.ErrorResponses = new MyErrorResponseProvider();

However; I am not quite getting how can I customize the default error responses in MyErrorResponseProvider class. Can somebody please provide me with any example so I can get started with this?

Thanks in advance!


回答1:


Found the way of implementing above as -

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 );
}
}

Thanks to github issue @ - https://github.com/Microsoft/aspnet-api-versioning/issues/233



来源:https://stackoverflow.com/questions/49124472/customized-error-responses-for-apiversioning-errors-in-webapi-dotnet-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!