Reputation: 425
Good evening, everybody. Trying to implement Api Versioning for my project. Faced with the problem that receiving default errors template response for request. Look code 1
{
"error": {
"code": "UnsupportedApiVersion",
"message": "The HTTP resource that matches the request URI 'https://localhost:5003/v2.3' does not support the API version '2.3'.",
"innerError": null
}
}
But I have my own error response template that want to receive.
{
"traceId": "0HMF1NONVN8SF:00000002",
"errors": [
{
"message": "",
"source": ""
}
]
}
As I understand I could implement my own ErrorResponseProvider, but could I avoid doing that?
How could I can disable ErrorResponse for ApiVersionOptions? My api version configuration:
services
.AddApiVersioning(opt =>
{
opt.ApiVersionReader = new UrlSegmentApiVersionReader();
opt.UseApiBehavior = false;
opt.DefaultApiVersion = ApiVersion.Default;
opt.AssumeDefaultVersionWhenUnspecified = true;
})
.AddVersionedApiExplorer(opt =>
{
opt.GroupNameFormat = "'v'VV";
opt.SubstituteApiVersionInUrl = true;
});
Versions:
.NET 6
ASP.NET Core 6
Microsoft.AspNetCore.Mvc.Versioning 5
Upvotes: 2
Views: 997
Reputation: 425
Actually I didn't find the way to disable it. However, I found the solution for my case. First of all, I implemented my CustomErrorResponseProvider for ErrorResponses.
public class CustomErrorResponseProvider : DefaultErrorResponseProvider
{
public override IActionResult CreateResponse(ErrorResponseContext context)
{
switch (context.ErrorCode)
{
case "UnsupportedApiVersion":
throw new UnsupportedApiVersionException("Url", context.Message);
}
return base.CreateResponse(context);
}
}
Than started throw necessary exception from it. And that's all!
As my middleware looks like this(img below), my ErrorHandlingMiddleware didn't catch an exception, because it was generated by default api versioning error handler.
Upvotes: 2