Site icon JD Bots

Creating Middleware in ASP.NET Core Web API with .NET 8: A Comprehensive Guide

Learn how to create custom middleware in ASP.NET Core Web API using .NET 8 in Visual Studio. This guide covers concepts, step-by-step instructions, and code examples.

Middleware in ASP.NET Core is an essential part of the request processing pipeline, handling everything from logging and authentication to response compression. In this guide, we will explore how to create and use custom middleware in an ASP.NET Core Web API application using .NET 8 in Visual Studio.

Concepts

Middleware

Middleware components in ASP.NET Core are software components that are assembled into an application pipeline to handle requests and responses. Each middleware component can either:

Request Pipeline

The request pipeline is a sequence of middleware components through which an HTTP request flows. Each component has the opportunity to process requests and responses.

RequestDelegate and Next

Step-by-Step Guide to Creating Custom Middleware

Step 1: Create a New ASP.NET Core Web API Project

  1. Open Visual Studio.
  2. Select Create a new project.
  3. Choose ASP.NET Core Web API and click Next.
  4. Name your project (e.g., MyMiddlewareApp) and choose a location. Click Next.

5. Select the latest .NET version (e.g., .NET 8) and click Create.

Step 2: Create the Middleware Class

  1. Right-click on the project in Solution Explorer.
  2. Select Add > New Folder and name it Middleware.
  3. Right-click on the Middleware folder, select Add > Class, and name it CustomMiddleware.

Here’s how the CustomMiddleware.cs should look:

namespace MyMiddlewareApp.Middleware
{
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<CustomMiddleware> _logger;

        // Constructor takes a RequestDelegate as a parameter
        public CustomMiddleware(RequestDelegate next, ILogger<CustomMiddleware> logger)
        {
            _next = next; // This represents the next middleware in the pipeline
            _logger = logger;
        }

        // InvokeAsync method processes the HTTP request
        public async Task InvokeAsync(HttpContext context)
        {
            // Code to execute before the next middleware
            _logger.LogInformation("Middleware executing before next...");

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

            // Code to execute after the next middleware
            _logger.LogInformation("Middleware executing after next");
        }
    }
}

Explanation:

Step 3: Register the Middleware

  1. Open the Program.cs file.
  2. Modify the to use your middleware.

Here’s the updated Program.cs:

using MyMiddlewareApp.Middleware;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

// Register your custom middleware
app.UseMiddleware<CustomMiddleware>();

app.Run();

Explanation:

Step 4: Run the Application

  1. Press F5 or click Start in Visual Studio to run the application.

Step 5: Test the Middleware

  1. Open a browser or use a tool like Postman.
  2. Send a request to the API (e.g., https://localhost:7155/WeatherForecast).

You should see the messages from your middleware in the response.

Complete Example

CustomMiddleware.cs:

namespace MyMiddlewareApp.Middleware
{
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<CustomMiddleware> _logger;

        // Constructor takes a RequestDelegate as a parameter
        public CustomMiddleware(RequestDelegate next, ILogger<CustomMiddleware> logger)
        {
            _next = next; // This represents the next middleware in the pipeline
            _logger = logger;
        }

        // InvokeAsync method processes the HTTP request
        public async Task InvokeAsync(HttpContext context)
        {
            // Code to execute before the next middleware
            _logger.LogInformation("Middleware executing before next...");

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

            // Code to execute after the next middleware
            _logger.LogInformation("Middleware executing after next");
        }
    }
}

Program.cs:

using MyMiddlewareApp.Middleware;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

// Register your custom middleware
app.UseMiddleware<CustomMiddleware>();

app.Run();

By following these steps, you’ll have a working middleware in your ASP.NET Core Web API application that intercepts requests and responses to add custom processing. This powerful mechanism allows you to handle a variety of tasks such as logging, authentication, and error handling in a modular and reusable way.

Source Code:

The application used above can be accessed from our public repository.


Exit mobile version