Vaughan Reid's blog

Using in-line middleware in ASP.NET Core

I previously showed how you can create your own middleware and use the app.UseMiddleware method to insert it into the pipeline.

For simple cases you can create inline middleware right in your Startup.Configure method. There are three options available.

Use: This can enrich a request context as it passes through the pipeline.


 app.Use(async (context, next) =>
            {
                //Do something on the request direction
                await next.Invoke();
                //Do something on the response direction
            });

Run: This should generate a response.


app.Run(async context =>
            {
                await context.Response.WriteAsync("This is now the final response.");
            });

Map: This can divert the pipeline in a different direction and potentially then use a Run to generate another response.


 app.Map("test", app =>
            {
                app.Use(async (context, next) =>
                {
                    //Maybe additional logging or enriching for the the test endpoint
                    await next.Invoke();
                });
            });