;

Master Middleware in .NET Core with Examples


Tutorialsrack 23/02/2025 C# ASP.NET Core

Introduction to Middleware in .NET Core

Middleware is a crucial component in ASP.NET Core applications that allows developers to handle requests and responses efficiently. It provides a way to build modular, reusable components that can execute logic before or after processing an HTTP request.

In this post, we'll explore what middleware is, how it works, and how to create custom middleware components. We'll also look at built-in middleware and real-world examples.

What is Middleware?

Middleware in .NET Core is software that is executed on every request made to an application. It can:

  • Modify request and response objects
  • Handle authentication and authorization
  • Log information
  • Redirect requests
  • Terminate request processing early

Example:

Middleware components are configured in the Program.cs file (or Startup.cs in older .NET Core versions) within the request pipeline:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Use(async (context, next) =>
{
    Console.WriteLine("Incoming request: " + context.Request.Path);
    await next.Invoke();
    Console.WriteLine("Outgoing response: " + context.Response.StatusCode);
});

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello, Middleware!");
});

app.Run();

This middleware logs request and response details before forwarding the request.

How Middleware Works in the Request Pipeline

Middleware components are executed in the order they are registered. Each middleware can:

  • Process the request
  • Call the next middleware in the pipeline
  • Short-circuit the pipeline (preventing further processing)

Middleware Execution Flow:

Request -> Middleware 1 -> Middleware 2 -> Middleware 3 -> Response

If a middleware terminates the request, the remaining components will not execute.

Creating Custom Middleware in .NET Core

You can create custom middleware as an inline delegate, a separate class, or an extension method.

Inline Middleware Example:

app.Use(async (context, next) =>
{
    Console.WriteLine("Custom Middleware Executed");
    await next.Invoke();
});

Custom Middleware Class:

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine("Request handled by custom middleware");
        await _next(context);
    }
}

Register the middleware in Program.cs:

app.UseMiddleware<CustomMiddleware>();

Built-in Middleware in .NET Core

ASP.NET Core provides many built-in middleware components, including:

  • Routing Middleware: Handles URL routing.
  • Authentication Middleware: Manages authentication mechanisms.
  • Authorization Middleware: Controls access permissions.
  • CORS Middleware: Handles Cross-Origin Resource Sharing.
  • Static File Middleware: Serves static files (CSS, JS, images).
  • Exception Handling Middleware: Catches and handles application errors.

Example of using built-in middleware:

app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseStaticFiles();

Real-World Examples of Middleware Usage

Logging Middleware

Logging is essential for tracking request data.

public class LoggingMiddleware
{
    private readonly RequestDelegate _next;
    
    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    
    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine($"Request Path: {context.Request.Path}");
        await _next(context);
    }
}

Register it:

app.UseMiddleware<LoggingMiddleware>();

Authentication Middleware

Middleware can handle JWT authentication:

app.UseAuthentication();

Exception Handling Middleware

To handle global exceptions:

app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        context.Response.StatusCode = 500;
        await context.Response.WriteAsync("An error occurred!");
    });
});

Key Takeaways

  • Middleware is essential for handling requests and responses in .NET Core.
  • It can modify requests, authenticate users, log activities, and more.
  • Middleware is executed in the order it's added to the pipeline.
  • Custom middleware can be created to handle specific tasks.
  • .NET Core provides built-in middleware for routing, authentication, CORS, and more.

Summary

Mastering middleware in .NET Core is crucial for building scalable and maintainable applications. Whether using built-in middleware or developing custom middleware, understanding its role in the request pipeline ensures better performance and security.

Now, try creating custom middleware components in your .NET Core applications and see how they improve request handling!


Related Posts



Comments

Recent Posts
Tags