Understanding Middleware Components in ASP.NET Core

.net core middleware

Introduction

We are going to discuss about .Net core middleware concept, at the end of this article, you will understand the concept of below points:

  • What is Middleware?
  • How Middleware Works in ASP.NET Core?
  • Types of Middleware.
  • Middleware Ordering.
  • Middleware Ordering and Its Importance.
  • Key Methods: Run, Use, and Map.
  • Creating Custom Middleware.

1. What is Middleware?

.NET Core is a powerful and versatile framework for developing robust web applications, Middleware is a key feature of this framework, Middleware in ASP.NET Core refers to software components that are used to handle requests and responses within the HTTP request pipeline, Middleware is a component that operates between the web server and the application and enabled you to modify the incoming request and outgoing response, each piece of this .Net Core middleware is responsible to perform a specific task, such as logging, authentication.

Middleware operates using a pipeline model. When a new request arrived on our application, it will rough through a series of components before it reaches to the main application. Before passing the request to the next components it can be modified by any middleware components. Once request passes through all middleware components it will reach the application. In same way, if any response sends back to the client, it will also pass through a series of middleware components and this response also can be modified in between before it is sent back to the client.

2. How Middleware Works in ASP.NET Core

.Net Core middleware is a piece of code used in application pipeline to process and handle the request and responses.

Middleware can be build-in as part of the .Net Core framework, you can add via NuGet packages or can be build custom middleware. Middleware components are registered and configured in the Startup class of your application. Configure method of this class defines the HTTP request pipeline of an ASP.NET Core application. It consists of a sequence of request delegates called one after the other.

The following figure shows how a request passes through various middleware components.

Typically, each middleware component processes the incoming request and then passes it on to the next middleware for additional processing.

However, a middleware component can decide not to pass the request to the next middleware in the pipeline. This is called short-circuiting or terminating the request pipeline. Short-circuiting is useful for avoiding unnecessary work. For example, if a request is for a static file like an image, CSS file, JavaScript file etc., these static files middleware can handle and serve the request and then short-circuit the rest of the pipeline.

ASP.NET Core Web application default configuration of middleware in the Configure method of the Startup class.

				
					public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        // This middleware is used to report app runtime errors in a development environment.
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // This middleware catches exceptions thrown in a production environment.
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios; see https://aka.ms/aspnetcore-hsts.
        app.UseHsts(); // Adds the Strict-Transport-Security header.
    }

    // This middleware is used to redirects HTTP requests to HTTPS.
    app.UseHttpsRedirection();

    // This middleware is used to returns static files and short-circuits further request processing.
    app.UseStaticFiles();

    // This middleware is used to route requests.
    app.UseRouting();

    // This middleware is used to authorizes a user to access secure resources.
    app.UseAuthorization();

    // This middleware is used to add Razor Pages endpoints to the request pipeline.
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

				
			

ASP.NET Core framework provides some of the Built-in middleware components that we can easily add to the Configure method. Check out the Microsoft documentation.

3. Types of Middleware

Built-in Middleware

ASP.NET Core provides a variety of built-in middleware components that handle common tasks:

·        Logging Middleware: Logs information about requests and responses, which can be helpful for monitoring and debugging.

·        Authentication Middleware: Manages user authentication and authorization, ensuring that users have the necessary permissions to access resources.

·        Error Handling Middleware: Catches and processes exceptions that occur during request processing, allowing you to provide custom error pages or responses.

·        Static File Serving Middleware: Serves static files, such as images, CSS, and JavaScript, directly from the file system.

Custom Middleware

Custom middleware is used to add specific functionality to your application that isn’t covered by built-in middleware. This could include anything from adding custom headers to responses to processing special types of requests.

 For example, you might create custom middleware to track request metrics:

				
					public class MetricsMiddleware
{
    private readonly RequestDelegate _next;

    public MetricsMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Track request metrics here
        await _next(context); // Call the next middleware
    }
}

				
			

3. Middleware Ordering and Its Importance

Middleware components are executed in the order they are added to the pipeline. It’s important to add them in the right order, otherwise, wrong order affects the application’s behavior. Proper ordering is crucial for ensuring security, performance, and overall functionality.

The following middleware components are commonly used in applications and should be added in the recommended order:

3. Key Methods: Run, Use, and Map

ASP.NET Core uses three primary methods to configure middleware: Run, Use, and Map. Each method serves a specific purpose in the middleware pipeline.

  •  app.Use() Method 

The Use method adds middleware to the pipeline. It allows for the insertion of middleware that processes requests and then calls the next component in the pipeline.

				
					app.Use(async (context, next) =>
{
// Middleware logic here
await next(); // Call the next middleware
});

				
			
  •  app.Run() Method

This middleware component may expose Run[Middleware] methods that execute at the end of the pipeline. Typically, this acts as terminal middleware and is placed at the end of the request pipeline because it does not pass control to the next middleware.

				
					app.Run(async context =>
{
    await context.Response.WriteAsync("Hello from terminal middleware!");
});

				
			
  •  app.Map() Method

The Map method branches the request pipeline based on the request path. It allows for creating sub-pipelines that handle requests with specific path segments.

				
					app.Map("/admin", adminApp =>
{
    adminApp.Run(async context =>
    {
        await context.Response.WriteAsync("Admin Area");
    });
});

				
			

3. Creating a Custom Middleware

Creating custom middleware involves defining a class that handles HTTP requests and responses. Here’s a step-by-step guide:

1.      Define the Middleware Class

      Create a class that implements the middleware logic. This class should have a constructor that accepts a  RequestDelegate and an InvokeAsync method.

				
					public class CustomMiddleware
{
    private readonly RequestDelegate _next;

    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Custom logic
        await context.Response.WriteAsync("Custom Middleware!\n");
        await _next(context); // Call the next middleware
    }
}

				
			

2.      Register the Middleware

       In the Startup class, register the middleware using the UseMiddleware method.

				
					public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<CustomMiddleware>();
    // Other middleware registrations
}
				
			

Summary

Middleware in ASP.NET Core manages how your web application handles HTTP requests. To summarize:

  • Each middleware component has access to both the incoming request and the outgoing response.
  • It can either pass the request to the next middleware in the pipeline or process it further.
  • It may perform additional processing before passing the request along.
  • It can terminate (short-circuit) the request pipeline when needed.
  • Middleware components are executed in the order they are added to the pipeline.

 

I hope this helps you understand middleware better! Happy learning!

Scroll to Top