NashTech Blog

Implementing Custom Middleware in .NET 8 for Azure Web Apps

Table of Contents

Introduction

ASP.NET Core’s middleware architecture offers a flexible pipeline model for handling HTTP requests, allowing developers to insert custom logic for tasks like logging, authentication, and error handling. In this post, we’ll delve into implementing custom middleware in .NET 8, testing it locally, and deploying it to Azure Web Apps, providing you with practical insights into middleware’s role and application in real-world scenarios.

What is Middleware?

Middleware is a piece of code that is executed on every HTTP request and response. It is a fundamental part of the ASP.NET Core request pipeline. Each middleware component can perform operations before and after the next middleware component in the pipeline is invoked. This makes middleware an ideal solution for adding cross-cutting concerns such as:

  • Logging: Recording request details for monitoring and diagnostics.
  • Authentication: Verifying user identities.
  • Error Handling: Managing exceptions and providing user-friendly error messages.
  • Request Modification: Altering requests or responses.

Middleware Pipeline

The middleware pipeline is configured in the Program.cs file of an ASP.NET Core application. Middleware components are added to the pipeline using extension methods that call UseMiddleware<T>(), where T is the middleware class. The order of middleware registration is crucial, as it determines the sequence in which they are executed.

Step for Implementing Custom Middleware

In this section, we will create a custom middleware that logs the request path and the time taken to process the request. This will illustrate how to create, register, and test middleware in a .NET 8 application.

Step 1: Create a New .NET 8 Web Application

  1. Open Visual Studio (or VS Code) and create a new project.
  2. Select ASP.NET Core Web App and choose .NET 8 as the framework.
  3. Name your project (e.g., CustomMiddlewareExample) and click Create.This generates a basic ASP.NET Core project with a standard setup.

Step 2: Define Your Custom Middleware

  1. Create a new class file for the middleware:
    • In Solution Explorer, right-click the project and select Add > New Folder. Name it Middleware.
    • Right-click the Middleware folder and select Add > Class. Name it RequestLoggingMiddleware.cs.
  2. Add the following code to RequestLoggingMiddleware.cs:
using Microsoft.AspNetCore.Http;
using System.Diagnostics;
using System.Threading.Tasks;

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        var stopwatch = Stopwatch.StartNew();

        // Log request path
        Console.WriteLine($"Handling request: {context.Request.Path}");

        // Call the next middleware in the pipeline
        await _next(context);

        stopwatch.Stop();
        var processingTime = stopwatch.ElapsedMilliseconds;

        // Log response time
        Console.WriteLine($"Finished handling request: {context.Request.Path}. Processing time: {processingTime}ms");
    }
} 
  • The RequestLoggingMiddleware class has a constructor that accepts a RequestDelegate parameter, representing the next middleware in the pipeline.
  • The InvokeAsync method logs the request path before calling the next middleware and logs the processing time after it.

Create an extension method to simplify middleware registration:

  • Add a new class file in the Middleware folder named RequestLoggingMiddlewareExtensions.cs.
using Microsoft.AspNetCore.Builder;

public static class RequestLoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestLogging(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestLoggingMiddleware>();
    }
}

This extension method provides a convenient way to register the middleware in the application’s pipeline.

Step 3: Register Middleware in Program.cs

  1. Open Program.cs and configure the middleware:
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

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

// Register custom middleware
app.UseRequestLogging();          // call adds the custom middleware to the pipeline.

app.MapControllers();

app.Run(); 

Testing Locally

  1. Run the application locally:
    • Press F5 in Visual Studio or use dotnet run from the terminal.
  2. Access the application:
    • Open your browser and navigate to http://localhost:5000 (or the port specified in your terminal).
  3. Check the console output:
    • Observe the console for logs indicating request paths and processing times.

Deploying to Azure Web Apps

  1. Publish your application:
    • Right-click your project in Visual Studio and select Publish.
    • Choose Azure as the target and follow the setup prompts for Azure Web Apps.
  2. Configure Azure Web App:
    • Go to the Azure portal and navigate to your Web App.
    • Adjust settings and environment variables as needed.
  3. Deploy:
    • Click Publish in Visual Studio to deploy your application to Azure.

Verify Middleware Execution on Azure

  1. Access your deployed Azure Web App using the provided URL.
  2. Check the Azure portal for logs:
    • Navigate to App Service and use Logs or Streaming logs to view output from your middleware.

Conclusion

Implementing custom middleware in .NET 8 allows you to inject custom logic into the HTTP request pipeline. By following this guide, you’ve learned how to create and deploy custom middleware that logs request paths and processing times, demonstrating a real-world application of middleware. For more advanced scenarios, consider exploring additional middleware functionalities or integrating with other services.

Picture of akshaychirde

akshaychirde

Leave a Comment

Suggested Article

Discover more from NashTech Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading