Why is ASP.NET Core executing a custom middleware only once?
Startup.Configure()
is executed once during app startup. It is used to make preparations for the application, it is not executed with every call. You can however use it to setup a middleware that is executed with every call. The microsoft documentation for asp.net core application startup contains a few examples both Configure
and ConfigureServices
.
The middlewares must be set up before calling app.UseMvc()
.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
// Forward to the next one.
await next.Invoke();
});
// !! Have to be called after setting up middleware !!
app.UseMvc();
}
This information is present in the documentation but I was not aware that it was applicable to custom middlewares as well:
The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.
The following Startup.Configure method adds middleware components for common app scenarios:
1 - Exception/error handling
2 - HTTP Strict Transport Security Protocol
3 - HTTPS redirection
4 - Static file server
5 - Cookie policy enforcement
6 - Authentication
7 - Session
8 - MVC
Update
In ASP.Net Core 3.0, you need to add your middleware before MapControllers()
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});