[ASP.NET Core] Middleware

The “Middleware” pipeline is the main mechanism of ASP.NET Core to process the request and create the response.

 

1. Middleware

The basic processing model (design) of ASP.NET Core is the pipeline

Middleware is a component that can be assembled into an application pipeline.

A request is passed to the first middleware in a pipeline and passes the result to the next middleware. The response will be passed in the reverse order.

[Note] Each Middleware delegates are configured using Run, Map, and Use extension methods.

 

2. IApplicationBuilder

IApplicationBuilder is responsible for creating a middleware pipeline.

The “Use()” is used to chain multiple request delegates and the “Run()” is used to terminate the pipeline.

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILogger logger)
{
    app.Use(async(context, next) =>
    {
        logger.LogInformation("Middleware 1 - Request");
        await next.Invoke();
        logger.LogInformation("Middleware 1 - Response");
    });

    app.Use(async (context, next) =>
    {
        logger.LogInformation("Middleware 2 - Request");
        await next.Invoke();
        logger.LogInformation("Middleware 2 - Response");
    });

    app.Run(async (context) =>
    {
        logger.LogInformation("Run - Request");
        await context.Response.WriteAsync("Hello World!");
        logger.LogInformation("Run - Response");

    });
}

This example shows how each middleware works in a pipeline.

In the “ASP.NET Core Web Server” Output screen, you can see the messages in this order:

Middleware 1 – Request
Middleware 2 – Request
Run – Request
Run – Response
Middleware 2 – Response
Middleware 1 – Response

 

3. Ordering

As we have seen in the previous example, the order that middleware components are added in the “Configure()” method is very important.

The general order of the middleware is

Exception/error handling -> Static file server -> Authentication -> MVC

Here is the default template code for ASP.NET Core MVC.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Exception Handling
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    // Support static files and some more
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    // Authentication
    app.UseAuthentication();

    // MVC
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s