Middlewares in ASP.Net Core

What is Middleware?

A Middleware is chain of function which are executed before the response of request being generated.

Middleware can do following:

  • Handle an incoming HTTP request by generating an HTTP response.

  • Process an incoming HTTP request, modify it, and pass it on to another piece of middleware.

  • Process an outgoing HTTP response, modify it, and pass it on to either another piece of middleware, or the ASP.NET Core web server.

Middleware are used for user authentication, logging, and error handling, etc.

Middleware are executed in the same order in which they are configured/added see following diagrams:

tesss.png

Middleware.png

Each Middleware is responsible for passing request to then next middleware using next method if it doesn’t pass to it’ll be considered as termination of middleware hence request passes it back through the pipeline.

Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.

What is Request Delegate?

The RequestDelegate type represents any Task returning method, which has a single parameter of type HttpContext.

ASP.NET Core request handling is achieved by chaining one or more RequestDelegate instances together.

What is HttpContext Object?

The ASP.NET Core web server constructs an HttpContext, which the ASP.NET Core application uses as a sort of storage box for a single request. Anything which is specific to this request and the subsequent response can be associated with and stored in it. This could include properties of the request, request-specific services,header, data which has been loaded, or errors which have occurred.

Create a middleware pipeline with IApplicationBuilder:

The Configure method calls once the when application starts and constructs the request pipeline IApplicationBuilder has methods for creating middlewares.

Methods are:

  • Use
  • Map
  • Run

Use Method:

This method is used to allow the request delegate to pass the request to the next middleware in the pipeline.

Map Method:

Map method branch the request pipeline with the mentioned URL In simpler words, this should be used in some specific cases where you want to map something to a special URL. If match found then rest of Middlewares won’t be considered in pipeline.

Run Method:

Run method used to end the pipeline registrations and acts as a final step. In simpler words, this should be used at the very last step of the pipelines when you want to start the actual application.

Examples:

Using app.Use method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
        app.Use(async (context,next)=>{
            await context.Response.WriteAsync(“Before Middleware”);
            await next()
         });
}

The app.Use gets two arguments. One is HttpContext and the second one is a RequestDelegate, which is basically the reference to the next middleware.

Using app.Map method:

public class Startup {
    private static void HandleFirstBranch(IApplicationBuilder app)    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("First Branch");
        });
    }

    private static void HandleSecondBranch(IApplicationBuilder app) {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Second Branch");
        });
    }

    public void Configure(IApplicationBuilder app) {
        app.Map("/map1",HandleFirstBranch);

        app.Map("/map2", HandleSecondBranch);

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from non-Map delegate. <p>");
        });
    }
}

if any requests start with /map1 url then request will be gone HandleFirstBranch middlware and same for /map2

Using app.Run Method:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
                await next.Invoke();

        });

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

Thanks for reading my post 😉.

Lots of ❤ from India.