Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
Why are Middleware Components Called Twice in a .Net Core Pipeline?

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:

  1. In the first app.Use(), await next.Invoke() is called
  2. In the second app.Use(), wait next.Invoke() is called
  3. App.Run() is called

Then, it comes back through the pipeline..

  1. In the second app.Use(), int j = 0 is called
  2. In the first app.Use(), int i = 0 is called

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

Chrome Dev Tools (F12 or Ctr + Shift + I shortcut)

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!