DEV Community

Fabrício Marcondes Santos
Fabrício Marcondes Santos

Posted on

Unraveling Middlewares in .NET

Introduction
Imagine driving in a busy city. Traffic officers are strategically positioned to direct and control the flow of vehicles, ensuring everyone reaches their destination safely and efficiently. Similarly, middlewares in .NET act like these traffic officers, directing and controlling the flow of data in an application.

In today's post, we'll explore the concept of middlewares, understand how they work, and discover why they are fundamental to the architecture of .NET applications.

What Are Middlewares?
Middlewares are software components that form a request and response processing pipeline in a web application. Each middleware can perform operations before and after passing the request to the next middleware in the pipeline. They are essential for tasks like authentication, logging, error handling, and more.

How Do Middlewares Work?
When a request arrives at the server, it passes through a series of middlewares, each performing a specific action. Think of it as a processing chain where each link can modify the request or response.

Here's a simple example of how to configure middlewares in .NET:

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

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have several middlewares configured in the pipeline, including HTTP redirection, static files, routing, authentication, and authorization.

Why Are They Important?
Middlewares are crucial to the architecture of .NET applications for several reasons:

  1. Modularity: They allow functionalities to be broken down into small, reusable components.

  2. Flexibility: You can easily add, remove, or reorder middlewares to change the application's behavior.

  3. Maintainability: They simplify maintenance and evolution of the application by isolating responsibilities.

Practical Example
Let's create a simple middleware that logs the processing time of each request:

public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        var watch = Stopwatch.StartNew();
        await _next(context);
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;
        Console.WriteLine($"Request took {elapsedMs} ms");
    }
}

public static class RequestTimingMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestTiming(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestTimingMiddleware>();
    }
}
Enter fullscreen mode Exit fullscreen mode

And to register this middleware in the pipeline:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseRequestTiming();
    // Other middlewares...
}
Enter fullscreen mode Exit fullscreen mode

Conclusion
Just as traffic officers control and direct the flow of vehicles, middlewares in .NET manage the flow of data, ensuring your application runs efficiently and securely. Understanding and utilizing middlewares is essential for developing robust and scalable web applications.

Top comments (0)