Reputation: 41
Developing an API platform that needs to be consistent through App Service itself and covering Azure API Management Service - I found myself stuck with an inconsistencies between both.
Sending a request with improper HTTP verb (e.g. PUT instead of POST) to API Management service results with 404 Not found response (due to a known issue).
Sending same request directly to ASP Core 2.2 based app would result in 405 Not Allowed response.
Is there any possibility in ASP Core (possibly middleware) to catch 405 response code result and change it to 404?
Upvotes: 2
Views: 3406
Reputation: 93273
This is something that you can handle with the StatusCodePages
middleware. Here's an example:
app.UseStatusCodePages(ctx =>
{
if (ctx.HttpContext.Response.StatusCode == 405)
ctx.HttpContext.Response.StatusCode = 404;
return Task.CompletedTask;
});
The argument passed into UseStatusCodePages
is a callback function that is executed whenever the middleware detects a response with a status code between 400 and 599 (with an empty body). In the example above, we simply check for 405
and change it to 404
. The call to UseStatusCodePages
itself must be placed before any request-handling middleware, such as MVC.
Upvotes: 1
Reputation: 2391
Not sure if I'm a fan of just doing blind status code conversion. Up to you based on your exact scenario, of course.
This bit of middleware injected in your Configure
method would do the trick:
public void Configure(IApplicationBuilder app)
{
app.Use(next => context =>
{
context.Response.OnStarting(() =>
{
if (context.Response.StatusCode == 405)
{
context.Response.StatusCode = 404;
}
return Task.CompletedTask;
});
return next(context);
});
}
NOTE: Add this early in the chain.
Upvotes: 3