Why does this work as expected:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRequestTimeoutMiddleware();
app.UseExceptionHandlingMiddleware();
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
but this, does not:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseRequestTimeoutMiddleware();
app.UseExceptionHandlingMiddleware();
}
On the second case, the InvokeAsync
is never called, that's what I mean by doesn't work.
It has to do with the way ASP.NET Core middleware ordering works. Microsoft has some great documentation here regarding middleware ordering, but for the sake of these docs changing I'll copy some of it to here.
Review the middleware execution order below:
You can see the order in which ASP.NET Core executes through the middleware pipeline, with the endpoint routing being the last thing in the execution order. By placing your custom middleware after the endpoint routing, it's essentially being short-circuited at that point and never being hit (as it traverses back up the execution chain).
From the link above, the docs state:
The order is critical for security, performance, and functionality.
To the love of some and hate of others, the convention is a bit of a gotcha when it comes to expected behavior.