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.
[Fact]
public async Task InvalidApiKey_ReturnsExpectedMessage()
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(
new Dictionary<string, string?>
{
["ApiKey"] = "secret-key"
})
.Build();
RequestDelegate next = context =>
Task.CompletedTask;
var middleware = new ApiKeyMiddleware(
next,
configuration);
var context = CreateContext();
await middleware.InvokeAsync(context);
context.Response.Body.Position = 0;
using var reader = new StreamReader(
context.Response.Body);
var response = await reader.ReadToEndAsync();
Assert.Equal("Invalid API key.", response);
}The stream position is reset before reading because middleware has already written data into the stream.
Without resetting the position, the reader may start at the end and return an empty string.
Testing Middleware That Uses Dependency Injection
Real middleware often depends on services such as logging, configuration, tenant providers, or request validation services.
These dependencies can be provided directly through the constructor or method parameters.
Consider middleware that uses a request identifier service.
public interface IRequestIdentifier
{
string GetIdentifier();
}
public class RequestIdentifier : IRequestIdentifier
{
public string GetIdentifier()
{
return Guid.NewGuid().ToString();
}
}The middleware adds the identifier to the response:
public class CorrelationMiddleware
{
private readonly RequestDelegate _next;
public CorrelationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(
HttpContext context,
IRequestIdentifier identifier)
{
var requestId = identifier.GetIdentifier();
context.Response.Headers["X-Correlation-ID"] =
requestId;
await _next(context);
}
}The test can provide a simple fake implementation:
public class FakeRequestIdentifier : IRequestIdentifier
{
public string GetIdentifier()
{
return "test-request-123";
}
}Now test the middleware:
[Fact]
public async Task Middleware_AddsCorrelationHeader()
{
var context = CreateContext();
RequestDelegate next = _ =>
Task.CompletedTask;
var middleware = new CorrelationMiddleware(next);
var identifier = new FakeRequestIdentifier();
await middleware.InvokeAsync(
context,
identifier);
Assert.Equal(
"test-request-123",
context.Response.Headers["X-Correlation-ID"]);
}This test verifies the middleware's behavior without registering the service in a dependency injection container.
That is useful when the middleware has a small number of dependencies.
For more complicated middleware, a lightweight service provider can be created when testing dependency resolution itself is part of the requirement.
Testing Middleware That Modifies the Response
Some middleware components modify response headers or status codes after the next component has executed.
For example, a middleware may add a security header:
public class SecurityHeaderMiddleware
{
private readonly RequestDelegate _next;
public SecurityHeaderMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await _next(context);
context.Response.Headers["X-Content-Type-Options"] =
"nosniff";
}
}A test can verify that the header is added after the next delegate completes.
[Fact]
public async Task Middleware_AddsSecurityHeader()
{
var context = CreateContext();
RequestDelegate next = async httpContext =>
{
await httpContext.Response.WriteAsync("Success");
};
var middleware = new SecurityHeaderMiddleware(next);
await middleware.InvokeAsync(context);
Assert.Equal(
"nosniff",
context.Response.Headers["X-Content-Type-Options"]);
}This verifies the middleware's behavior directly.
For middleware that depends on response headers being available after the response has started, tests should also account for the actual response lifecycle. In a real server, headers generally cannot be modified after the response has started.
Testing Middleware Exceptions
Exception-handling middleware should also be tested independently.
Consider the following implementation:
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception)
{
context.Response.StatusCode =
StatusCodes.Status500InternalServerError;
await context.Response.WriteAsync(
"An unexpected error occurred.");
}
}
}A test can provide a delegate that throws an exception:
[Fact]
public async Task Middleware_HandlesUnexpectedException()
{
var context = CreateContext();
RequestDelegate next = _ =>
throw new InvalidOperationException(
"Test exception");
var middleware = new ExceptionMiddleware(next);
await middleware.InvokeAsync(context);
Assert.Equal(
StatusCodes.Status500InternalServerError,
context.Response.StatusCode);
}This test verifies that the middleware catches the exception and produces the expected status code.
A production exception middleware should also log the original exception, avoid exposing sensitive exception details to clients, and handle the situation where the response has already started.
Unit Tests Versus Integration Tests
Testing middleware independently is useful, but it does not replace integration testing.
The two approaches validate different aspects of the application.
Area | Isolated Middleware Test | Integration Test |
|---|---|---|
Middleware logic | Excellent | Supported |
Request and response behavior | Directly testable | Tested through HTTP |
Middleware registration | Not verified | Verified |
Middleware execution order | Not fully verified | Verified |
Routing interaction | Not verified | Verified |
Authentication configuration | Limited | Can be tested |
Complete request pipeline | Not covered | Covered |
For example, a unit test may prove that API key middleware rejects an invalid key.
However, it does not prove that the middleware was correctly registered in Program.cs.
It also does not verify whether another middleware component runs before or after it.
For these scenarios, use integration tests with WebApplicationFactory or TestServer.
A balanced testing strategy uses isolated tests for detailed middleware behavior and integration tests for pipeline configuration.
Best Practices for Middleware Testing
Keep Tests Focused
Each test should verify one meaningful behavior.
For example, separate tests should verify invalid requests, valid requests, missing headers, and response modification.
This makes failures easier to understand.
Test Whether the Next Delegate Executes
For middleware that can stop the request pipeline, always verify whether the next delegate was called.
This is particularly important for authentication, authorization, request validation, and rate-limiting middleware.
Use Cancellation Tokens Where Required
If middleware performs asynchronous operations, test how it behaves when the request is cancelled.
Cancellation should be propagated to downstream operations wherever appropriate.
Avoid Unnecessary Mocking
Use simple delegates and fake implementations for small dependencies.
A full mocking framework is not always required to test middleware behavior.
Include Integration Tests
Test the actual middleware registration, ordering, and interaction with routing and authentication.
Isolated tests and integration tests complement each other.
Common Mistakes to Avoid
Mistake | Why It Is a Problem | Better Approach |
|---|---|---|
Starting the full application for every middleware test | Adds unnecessary setup | Use DefaultHttpContext for isolated tests |
Ignoring the next delegate | Does not verify pipeline behavior | Track whether the delegate executes |
Forgetting to assign a response MemoryStream | Makes response-body assertions difficult | Configure the response stream explicitly |
Not resetting stream position | Tests may read an empty response | Set Position to zero before reading |
Testing only successful requests | Failure behavior remains unverified | Test valid, invalid, and exceptional scenarios |
Testing middleware in isolation only | Registration and ordering issues remain undetected | Add integration tests |
Using real external services in unit tests | Makes tests slower and less predictable | Use fakes or controlled test dependencies |
Summary
ASP.NET Core middleware can be tested without starting the complete application by creating an HttpContext, providing a RequestDelegate, and invoking the middleware directly.
DefaultHttpContext makes it possible to test request headers, response status codes, response bodies, and other HTTP-related behavior without hosting a web server.
This approach is especially useful for custom authentication middleware, request validation, correlation identifiers, security headers, and exception handling.
However, isolated middleware tests do not verify the complete ASP.NET Core request pipeline. Middleware registration, execution order, routing, and authentication integration should also be covered by integration tests.
Combining focused middleware tests with a smaller set of integration tests creates a reliable testing strategy without introducing unnecessary application startup overhead.


Join the conversation! Your thoughts help the community grow.