问题
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