Middleware is one of the most important parts of the ASP.NET Core request pipeline. It handles cross-cutting responsibilities such as authentication, authorization, exception handling, logging, request validation, rate limiting, and response modification.
In a typical ASP.NET Core application, middleware components are registered in Program.cs and execute whenever an HTTP request passes through the application.
As an application grows, middleware often contains important business-related infrastructure logic. A custom middleware component may inspect request headers, identify a tenant, validate an API key, add correlation information, or handle exceptions.
Testing this behavior is important because a middleware issue can affect multiple endpoints rather than a single controller.
A common approach is to write integration tests that start the complete ASP.NET Core application using a test server. This is useful for validating the entire request pipeline, but it may be unnecessary when the goal is to test one small middleware component.
ASP.NET Core middleware can also be tested independently by creating an HttpContext, providing a mock or test implementation of the next request delegate, and invoking the middleware directly.
This approach makes focused tests faster to write, easier to understand, and useful for checking specific request and response behavior.
In this article, we will explore how middleware works, how to test it without starting the complete application, and when isolated tests should be combined with integration tests.
Understanding How ASP.NET Core Middleware Works
Middleware components are arranged in a request-processing pipeline.
Each middleware receives an HttpContext and a RequestDelegate representing the next component in the pipeline.
A simplified middleware implementation looks like this:
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
public RequestLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
Console.WriteLine(
$"Request: {context.Request.Method} {context.Request.Path}");
await _next(context);
}
}The constructor receives the next middleware component. The InvokeAsync method executes when a request reaches this middleware.
The call to _next(context) passes control to the next component.
Middleware can also perform work after the next component completes:
public async Task InvokeAsync(HttpContext context)
{
Console.WriteLine("Request started");
await _next(context);
Console.WriteLine("Request completed");
}This structure creates two important testing scenarios:
Verify what middleware does before calling the next component.
Verify what middleware does after the next component completes.
A middleware component may also stop the pipeline entirely. For example, an API key middleware can return an unauthorized response without calling the next delegate.
These behaviors can be tested independently.
Why Test Middleware Without Starting the Application?
Starting the complete ASP.NET Core application for every middleware test can introduce unnecessary setup.
An integration test may need application configuration, dependency injection, database services, authentication settings, and a test server.
However, a middleware component that only checks a request header does not need all those dependencies.
Consider a custom middleware that validates an API key.
Its responsibility is relatively small:
Read the API key from the request header.
Compare it with the configured key.
Return an unauthorized response if validation fails.
Continue the request pipeline when validation succeeds.
A focused unit test can verify these behaviors without starting controllers, routing, or the complete application.
This approach also makes failures easier to diagnose because the test focuses on one middleware component.
Creating a Custom API Key Middleware
Let's implement a simple middleware component that validates an API key.
The middleware will expect a header named X-API-Key.
public class ApiKeyMiddleware
{
private readonly RequestDelegate _next;
private readonly string _expectedApiKey;
public ApiKeyMiddleware(
RequestDelegate next,
IConfiguration configuration)
{
_next = next;
_expectedApiKey =
configuration["ApiKey"] ?? string.Empty;
}
public async Task InvokeAsync(HttpContext context)
{
var apiKey = context.Request.Headers["X-API-Key"]
.FirstOrDefault();
if (string.IsNullOrWhiteSpace(apiKey) ||
apiKey != _expectedApiKey)
{
context.Response.StatusCode =
StatusCodes.Status401Unauthorized;
await context.Response.WriteAsync(
"Invalid API key.");
return;
}
await _next(context);
}
}The middleware reads the expected API key from configuration.
If the request does not contain a valid key, it returns HTTP 401 and stops further processing.
If the key is valid, it calls the next request delegate.
For a production API, do not rely on a simple string comparison as the only security control. Use an established authentication mechanism where appropriate, protect secrets, and apply consistent authorization policies. This example is intended to demonstrate middleware testing.
Creating a Test Project
Create a separate test project:
dotnet new xunit -n MiddlewareTestsAdd a project reference to the ASP.NET Core application:
dotnet add MiddlewareTests reference ../YourApi/YourApi.csprojThe test project can use the ASP.NET Core HTTP abstractions without starting a web server.
If the application uses IConfiguration, the test can provide an in-memory configuration instead of loading the complete application configuration.
The following namespaces will be useful:
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Xunit;Testing Middleware With DefaultHttpContext
ASP.NET Core provides DefaultHttpContext, which is useful for creating an HttpContext directly inside a test.
It provides access to request headers, response status codes, response bodies, and other HTTP-related properties.
We can create a context without hosting an ASP.NET Core application.
First, create a helper method:
private static DefaultHttpContext CreateContext()
{
var context = new DefaultHttpContext();
context.Response.Body = new MemoryStream();
return context;
}The response body is assigned a MemoryStream so the test can inspect the content written by middleware.
This is important because the default response body is not automatically configured as a readable test stream.
Testing an Invalid API Key
The first test verifies that a request without a valid API key receives an unauthorized response.
[Fact]
public async Task InvalidApiKey_ReturnsUnauthorized()
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(
new Dictionary<string, string?>
{
["ApiKey"] = "secret-key"
})
.Build();
var nextCalled = false;
RequestDelegate next = context =>
{
nextCalled = true;
return Task.CompletedTask;
};
var middleware = new ApiKeyMiddleware(
next,
configuration);
var context = CreateContext();
await middleware.InvokeAsync(context);
Assert.Equal(
StatusCodes.Status401Unauthorized,
context.Response.StatusCode);
Assert.False(nextCalled);
}This test checks two important conditions.
First, the response status code must be 401.
Second, the next middleware component must not execute.
The second assertion is particularly useful because it verifies that invalid requests are stopped before reaching the rest of the pipeline.
Testing a Valid API Key
Now test the successful scenario.
[Fact]
public async Task ValidApiKey_CallsNextMiddleware()
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(
new Dictionary<string, string?>
{
["ApiKey"] = "secret-key"
})
.Build();
var nextCalled = false;
RequestDelegate next = context =>
{
nextCalled = true;
context.Response.StatusCode =
StatusCodes.Status200OK;
return Task.CompletedTask;
};
var middleware = new ApiKeyMiddleware(
next,
configuration);
var context = CreateContext();
context.Request.Headers["X-API-Key"] =
"secret-key";
await middleware.InvokeAsync(context);
Assert.True(nextCalled);
Assert.Equal(
StatusCodes.Status200OK,
context.Response.StatusCode);
}This test verifies that the middleware accepts the configured API key and passes control to the next component.
Notice that the test delegate is deliberately simple.
It does not need a controller or an actual HTTP server. It only needs to record whether it was called.
Testing the Response Body
Middleware sometimes writes custom error messages or diagnostic information into the response body.
Testing only the status code may not be sufficient.
We can read the response body from the MemoryStream.
Join the conversation! Your thoughts help the community grow.