If I create a blank ASP.net Web Core Application, then replace the Configure() method in Startup.cs with the following method, each Use() and Run() operation is called twice.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
int i = 0;
});
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
int j = 0;
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});
}
So the order of operations is:
Then, it comes back through the pipeline..
All of this is expected as it passes through the Middleware and back. But then, each of the above steps is repeated again.
Why is each middleware component called twice?
The reason it is called twice is that your browser is making two requests to your app. One for the app root path '/' the other one for /favicon.ico (some browsers like chrome makes favicon request by default, screenshot below). You can check your browser dev tools.
You can also verify that by putting a debug log inside app.Use to see the request paths. e.g.
app.Use(async (context, next) =>
{
Debug.WriteLine(context.Request.Path.Value);
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
int i = 0;
});
So your middleware setup runs twice. Once for root '/' and the second time for '/favicon.ico' path