Asp.net Core Middleware Example

In this tutorial, you will learn how to use middleware in Asp.net Core step by step, how to implement httpclient middleware, default middleware, custom default middleware etc.

What is Middleware in .Net Core?

"Middleware is software that's assembled into an app pipeline to handle requests and responses." -MSDN

Middleware is an external components that form a pipeline between a server and application, to inspect, route, modify request and response messages for that specific purpose.

Built-in Middleware and Custom Middleware

There are many built-in middleware in asp.net core framework, like (Session, Logging etc.) to use the middleware in application, we need to add the service services.AddSwaggerGen(); and use the service app.UseSwagger(); in app, like in example below we have configured API testing middleware Swagger.

var builder = WebApplication.CreateBuilder(args);

var services = builder.Services;
services.AddSwaggerGen();

var app = builder.Build();
app.UseSwagger();

We can develop a code with a purpose to manipulate the requests and responses.

Or you can say Middleware is a mechanism that allows to manipulate Http-Pipeline, which was not possible in earlier Asp.net Framework (HttpHandlers, HttpModules), you can read more about Asp.net Core Middleware.

Here we more focus on how to configure middleware using Run, Map, and Use extension methods.

Add .net Core Middleware in Pipeline

You can add Middleware in Pipeline using IApplicationBuilder, here we see how we can add a new service to Middleware, Some commonly used middleware are UseMvc(), UseAuthentication(), UseDeveloperExceptionPage()

Here are some example of default middleware, We simply can configure default middleware just by adding built in default extension methods in Configure method of startup file.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {     
    app.UseMvc();
    app.UseAuthentication();
    app.UseDeveloperExceptionPage();
    app.UseStaticFiles(); 
}		

Middlewares are executed in the order they are configured. You can change the order; the first configured middleware will get executed first.

Custom Middleware in Asp.net Core

You can build your custom middleware and add to request pipeline in Startup Configure method

Here are the namespace you required to create a custom Middleware, here in example we have created "WTRCustomMiddleware"

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
Create the Middleware class
public class WTRCustomMiddleware
{
private readonly RequestDelegate _next;
public WTRCustomMiddleware(RequestDelegate next)
{
    _next = next;
}

public async Task InvokeAsync(HttpContext context)
{
    await context.Response.WriteAsync("- Before Message -  \n\r");
    await _next(context);
    await context.Response.WriteAsync("\n\r - After Message - ");
}
}

Now add a static extensions class for extension method

    public static class WTRCustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseWTRCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<WTRCustomMiddleware>();
        }
    }

Now your custom middleware class is ready simply add to pipeline, open your startup.cs class, place the following code in Configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ app.UseWTRCustomMiddleware();
app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Welcome to WebTrainingRoom!");
    });
} 
Map Middleware for different path

We can implement different Middleware for different path, here is an example of two Middleware pipeline, we want to map them for different path.

private static void ExecuteMiddleware1(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Execute Middleware 1");
});
}
private static void ExecuteMiddleware2(IApplicationBuilder app)
{
app.Run(async context =>
    {
        await context.Response.WriteAsync("Execute Middleware 2");
    });
}

Here is how you can Map Middleware in Configure method

public void Configure(IApplicationBuilder app)
{
app.Map("/mapPath1", ExecuteMiddleware1);
app.Map("/mapPath2", ExecuteMiddleware2);
app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from No Match.");
        });
    }

Here are some more middleware examples you should look at, logging and exception handling are two frequently used functionalities in any application development lifecycle, in below tutorial you can learn how to use middleware for logging and error handling.

Asp.Net Core C# Examples | Join Asp.Net MVC Course