Asp.Net Core Middleware

Mevlüt Gür
2 min readMar 7, 2022

I learned something about middleware from this video. I wrote an article about this topic. I hope it will helpful.

Middleware are transactions that happen between request and response on web applications.

Middlewares are triggered like a spiral. So, it work like a recursive functions. If there is a next Middleware it`s continue. Else return previous middleware.

Middleware working principle

Asp.Net Core has a core to support middleware configuration.

When an Asp.Net Core application is launched, the Configure method is triggered.

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

Middleware trigger order is important. For example, we must call app.UseRouting() before app.UseEndpoints(…)

Middleware Types

Run Function

The run function does not trigger the middleware that follows it. It is called Short Circuit.

For example, when run below code.

app.Run(async context=> {Console.WriteLine(“Middleware 1”);});app.Run(async context=> {Console.WriteLine(“Middleware 2”);});

Console Output

Middleware 1

Use Function

While providing its own functionality, it also enables our next middleware call.

For example, when run below code.

app.Use(async (context,next)=>{Console.WriteLine(“Start use middleware”);await next.Invoke();Console.WriteLine(“Stop use middleware”);});app.Run(async context=> {Console.WriteLine(“Start run middleware”)};);

Console Output

Start use middleware

Start run middleware

Stop use middleware

Map Function

Sometimes you may have to run the middleware according to the endpoint of request.

For example, If you want to catch a request to the “/home” endpoint.

app.Map(“/home”,builder =>{builder.Run(async context => Console.WriteLine(“Hello”));});

Sometimes you may have to run the middleware according to the attribute of request.

For example, If you want to catch a GET request.

app.MapWhen(context=> context.Request.Method == “GET”,builder =>{builder.Use(async (context1, next) =>{Console.WriteLine(“Middleware”);await next.Invoke();});});

Custom Middleware Example

Create a custom middleware class that contain Invoke method.

public class CustomMiddleware{RequestDelegate _next;public CustomMiddleware(RequestDelegate next){_next = next;}public async Task Invoke(HttpContext httpContext){Console.WriteLine(“Custom middleware start”);await _next.Invoke(httpContext);Console.WriteLine(“Custom middleware end”);}}

Create a extension that call CustomMiddleware class.

public static class CustomMiddlewareExtension{public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder applicationBuilder){return applicationBuilder.UseMiddleware<CustomMiddleware>();}}

And call anywhere CustomMiddlewareExtension.

app.UseCustomMiddleware();

--

--