Middlewares in ASP .NET Core
.NET Core .NET

Middlewares in ASP .NET Core

Mishel Shaji
Mishel Shaji

In this post, we’ll learn about Middleware and how to create them. Middleware is a software component which is executed on every request and response in ASP .NET Core application.

In ASP .NET Core, you can add more than one Middleware. Each Middleware can process the request and then either choose to return the result or pass the control to next Middleware in the request pipeline.

asp .net core middleware

Table of Contents

Configuring a middleware

Middlewares are usually configured in the Configure method of Startup.cs class by calling Use***something** method of the IApplicationBuilder.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseMvc();
} 

UseStaticFiles(), UseMVC(), UseHttpsRedirection() etc are middlewares. They are executed in the order in which they are defined.

Middlewares are executed in the order in which they are defined.

Creating a middleware pipeline

Middlewares are created using the app.run(), app.use() methods.

app.run()

The run() method is used to add a middleware. The first run() method will terminate the request pipeline.

public void Configure(IApplicationBuilder app)
{
    app.Run(context => context.Response.WriteAsync("Hello World!"));
}

The above method blocks the thread until it’s execution is completed because it is not asynchronous. You can make it asynchronous by modifying it as:

public void Configure(IApplicationBuilder app)
{
    app.Run(async context => await context.Response.WriteAsync("Hello World!"));
}

app.use()

app.use() method is also used to create middlewares. Unlike app.run(), this method chains the middlewares in the request pipeline. Also, it has a next parameter that points to the next middleware in the request pipeline.

public void Configure(IApplicationBuilder app)
{
    app.Use(async (context, next) =>
    {
        //Do your magic here that does not add anything to the response.
        await next.Invoke();
    });
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Hello from 2nd delegate.");
    }); 
}

The Use method can short-circuit the pipeline if it does not pass the request to the next middleware.

When a middleware does not pass a request to the next middleware, it’s called short-circuiting the request pipeline.

app.map()

This method is used to branch the pipeline based on a given pattern that matches with the request URL.

public void Configure(IApplicationBuilder app)
{
    app.Map("/admin", HandleAdmin);
    app.Map("/user", HandleUser);
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Hello World.");
    });
}
private static void HandleAdmin(IApplicationBuilder app)
{
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Welcome Admin.");
    });
}
private static void HandleUser(IApplicationBuilder app)
{
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Welcome User.");
    });
}

Run the application and modify the URL’s as shown in the table below.

Request pathResponse
https://localhost:44304Hello World.
https://localhost:44304/adminWelcome admin.
https://localhost:44304/userWelcome user.