Middleware in .Net core

shariaretanvir

shariaretanvir

Posted on September 27, 2021

Middleware in .Net core

Asp.net core middleware is a software component integrated with application pipeline that we can use to handle http requests and responses. It’s a very important concepts in .net core environment. In .net core middleware are used in the configure method on startup class. We can also use custom middleware in that section. There are couple of ways to implement custom middleware which I will cover in another article.

There are mainly 3 methods by which we can manage middleware in our application.

Run()

This middleware is basically used at the end of the pipeline. It adds a terminal component in the pipeline. It has a single parameter which takes request delegates. It doesn’t has any next delegate as it terminates the pipeline.

Example

 app.Run(async context =>
   {
      await context.Response.WriteAsync("Started");
   });
Enter fullscreen mode Exit fullscreen mode

Here we use run method and in the output we will see Started. After executing run method no other middleware will be executed as it return back to the pipeline process.

Use()

To use multiple middleware we can use this method. It takes 2 parameters, one is request delegate another one is next delegates. Next is used to call the next middleware in the pipeline.

Example

app.Use(async (contect, next) => {
                await contect.Response.WriteAsync("Use middleware 1 start\n");
                await next.Invoke();
                await contect.Response.WriteAsync("Use middleware 1 end\n");
            });

            app.Use(async (context, next) => {
                await context.Response.WriteAsync("Use middleware 2 start\n");
                await next.Invoke();
                await context.Response.WriteAsync("Use middleware 2 end\n");
            });

            app.Run(async context =>
            {
                await context.Response.WriteAsync("Run middleware\n");
            });

            app.Use(async (context, next) => {
                await context.Response.WriteAsync("Use middleware 3 start\n");
                await next.Invoke();
                await context.Response.WriteAsync("Use middleware 3 end\n");
            });


Enter fullscreen mode Exit fullscreen mode

Here we can see multiple use middleware and those are communicating to each other. So in the postman output will be like this.

Use middleware 1 start
Use middleware 2 start
Run middleware
Use middleware 2 end
Use middleware 1 end

Enter fullscreen mode Exit fullscreen mode

One major thing to notice is that middleware 3 is not executing after run middleware. That’s because run doesn’t call next middleware and it terminates the cycle and return back to the upper middleware.

Map()

Map function is used to branch the middleware. When a request comes with a specific path then map function is execute. When the path get matched the in the map function we can use use and run method to execute the middleware.

app.Use(async (contect, next) => {
                await contect.Response.WriteAsync("Use middleware 1 start\n");
                await next.Invoke();
                await contect.Response.WriteAsync("Use middleware 1 end\n");
            });
            app.Map("/getdata", builder =>
            {
                builder.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("Map middleware start\n");
                    await next.Invoke();
                    await context.Response.WriteAsync("Map middleware end\n");
                });
                builder.Run(async (context) =>
                {
                    await context.Response.WriteAsync("Map Run middleware\n");
                });
            });


Enter fullscreen mode Exit fullscreen mode

So when we call /getdata we can see the following output.

Use middleware 1 start
Map middleware start
Map Run middleware
Map middleware end
Use middleware 1 end

Enter fullscreen mode Exit fullscreen mode

That’s because after the use function get called map middleware will get executed and in the map function there are two function. When run method get executed middleware get terminated and no other middleware will execute.

MapWhen()

Mapwhen function is used to branch the pipeline depending of the given predicate. When the condition returns true then this function executes.

app.Use(async (contect, next) => {
                await contect.Response.WriteAsync("Use middleware 1 start\n");
                await next.Invoke();
                await contect.Response.WriteAsync("Use middleware 1 end\n");
            });

app.MapWhen(context => context.Request.Query.ContainsKey("token"), builder =>
            {
                builder.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("Use map start\n");
                    await next.Invoke();
                    await context.Response.WriteAsync("use map end\n");
                });
                builder.Run(async context =>
                {
                    await context.Response.WriteAsync("use map run executes");
                });
            });


Enter fullscreen mode Exit fullscreen mode

If we request with the query string contains token then web can see the output given below.

postman

You can see the request link as it contains key name token.

If we have several middleware but not having token query string then those middleware will not execute.

So those are the core concepts of .net core middleware. We can use those concepts to build our custom middleware and use it to our application.

Image description

Summery

  1. Middleware is a component which has the ability to access incoming request and responses.
  2. It can communicate to another middleware.
  3. It has an order in which it executes.
  4. We can terminates middleware whenever we want to.
  5. Common functionality like log, exception handling, authentication, and authorization based components can be a proper example for using middleware. In the next article I will be covering how to create custom middleware and incorporate with the application.
💖 💪 🙅 🚩
shariaretanvir
shariaretanvir

Posted on September 27, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Middleware in .Net core
dotnet Middleware in .Net core

September 27, 2021