简体   繁体   中英

Why is ASP.NET Core executing a custom middleware only once?

I have an ASP.NET Core with the following controller that accepts a POST request:

[Route("api/v1/tenants/tests")]
public class TestsController : Controller
{
    [HttpPost]       
    public IActionResult Post(string tenantId)
    {
        return Ok();
    }
}

I have developed a 'null' middleware to test things out. It is defined in the Configure method of the Startup.cs file:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }

     app.UseMvc();

     app.Use(async (context, next) =>
     {
         // Forward to the next one.
         await next.Invoke();
     });
}

Question

When I call the controller via Postman, the initial call to the POST method goes successfully through the middleware and then to the Controller. However, the following calls directly go to the Controller, skipping the middleware entirely. Why is that?

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();
 });

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM