ASP.NET Core Custom Middleware and Security Headers
On this page
Learning Objective
Write reusable middleware classes, apply cross-cutting concerns such as correlation identifiers, security headers, and request timeouts, and reason about what an API returning JSON needs from response headers compared with an HTML page.
Concept Explanation
Inline app.Use lambdas are fine for a quick experiment, but a concern that matters, such as security headers or request correlation, deserves a class with a name, a test, and a single registration line. A middleware class has a constructor that receives the next delegate and an InvokeAsync method that takes the HttpContext, plus any per-request services as additional parameters. The framework constructs it once, so anything stored in its fields is shared by all requests and must be thread-safe, the same rule as singletons. You then register it with UseMiddleware and expose it as an extension method for readability.
The first cross-cutting concern worth having is a correlation identifier. Each request gets an ID, either taken from a well-formed incoming header or generated fresh, that is added to the response, attached to the logging scope, and forwarded on outbound calls. When a user reports a problem, that single value finds every log line across the system. It should be validated before use, since an incoming header is untrusted input: accept it only if it matches a safe pattern and length, otherwise replace it, so an attacker cannot inject newlines or huge values into your logs and downstream requests.
Security headers are the second. An API returning JSON has a simpler set than an HTML site, but a few matter: X-Content-Type-Options with the value nosniff stops browsers guessing that a response is executable content, Cache-Control with no-store on sensitive responses keeps personal data out of shared and browser caches, Referrer-Policy limits what leaks in the Referer header, and Strict-Transport-Security tells browsers to use HTTPS only. A restrictive Content-Security-Policy on API responses, such as default-src none with frame-ancestors none, costs nothing and protects against the rare case where a response is rendered as a document. Express developers know the helmet package; in .NET you write a few lines yourself or use a small library. The full theory behind these headers, including how CSP and CORS work, is covered in the Browser Security course elsewhere in this hub.
Timeouts complete the set. A request that runs forever ties up a thread, a database connection, and memory, and enough of them take a service down. Since .NET 8 the request timeouts middleware lets you apply a default and per-endpoint limits that trigger the request's cancellation token, which your code should already be passing down as Day 6 taught. Together, correlation, headers, and timeouts form the operational baseline for every API, applied once in the pipeline instead of remembered on each endpoint.
| Concern | Header or mechanism | Purpose |
|---|---|---|
| Traceability | X-Correlation-Id, validated | Find all logs for one request |
| MIME sniffing | X-Content-Type-Options: nosniff | Stop the browser guessing content types |
| Caching of private data | Cache-Control: no-store | Keep sensitive responses out of caches |
| Referrer leakage | Referrer-Policy: no-referrer | Do not leak URLs to other sites |
| Transport security | Strict-Transport-Security | Force HTTPS in browsers |
| Runaway requests | Request timeouts middleware | Bound resource use per request |
Worked Example: Correlation Id, Security Headers and Timeouts
The middleware class below validates or creates a correlation identifier, opens a logging scope, and sets security headers using OnStarting so they are added reliably before the response is sent. The registration adds request timeouts.
public sealed partial class RequestHardeningMiddleware(RequestDelegate next, ILogger<RequestHardeningMiddleware> logger)
{
private const string Header = "X-Correlation-Id";
[GeneratedRegex("^[A-Za-z0-9-]{8,64}$")]
private static partial Regex SafeId();
public async Task InvokeAsync(HttpContext context)
{
// Accept an incoming id only if it is short and made of safe characters.
var incoming = context.Request.Headers[Header].ToString();
var id = SafeId().IsMatch(incoming) ? incoming : Guid.NewGuid().ToString("N");
context.Response.OnStarting(() =>
{
var h = context.Response.Headers;
h[Header] = id;
h["X-Content-Type-Options"] = "nosniff";
h["Referrer-Policy"] = "no-referrer";
h["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'none'";
if (!h.ContainsKey("Cache-Control")) h["Cache-Control"] = "no-store";
return Task.CompletedTask;
});
using (logger.BeginScope(new Dictionary<string, object> { [Header] = id }))
{
await next(context);
}
}
}
// Program.cs
builder.Services.AddRequestTimeouts(o =>
{
o.DefaultPolicy = new RequestTimeoutPolicy { Timeout = TimeSpan.FromSeconds(15) };
o.AddPolicy("reports", TimeSpan.FromSeconds(60)); // a longer, named exception
});
var app = builder.Build();
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseMiddleware<RequestHardeningMiddleware>();
app.UseRequestTimeouts();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/api/reports/annual", GenerateReport).WithRequestTimeout("reports");Because the class is registered once, every endpoint, including ones added next year, gets the same baseline. A test can send a request with a malicious correlation header containing a newline and assert that the response contains a fresh, safe identifier instead.
Real-World Examples
- HTTP Strict Transport Security was standardized in RFC 6797 in 2012 in response to attacks that downgraded secure connections to plaintext, and browsers ship a preload list so that major sites are HTTPS-only from the first visit. The Strict-Transport-Security header your API emits is the server's half of that protection, and setting it in one middleware avoids forgetting it on some routes.
- Mozilla's Observatory scanner grades sites on the presence and quality of headers such as Content-Security-Policy, X-Content-Type-Options, Referrer-Policy, and Strict-Transport-Security, and is widely used as a quick baseline check in security reviews. A single hardening middleware is the simplest way to earn a passing grade consistently across an API.
Review Questions & Answers
It comes from an untrusted client, so it could contain newlines, extremely long values, or control characters intended to forge log entries or break downstream systems. Accepting it only when it matches a strict pattern and otherwise generating a new one keeps logs and outbound requests clean while still allowing legitimate upstream systems to propagate their identifiers.
Once the response body begins to be written, the headers have already been sent and can no longer be changed. OnStarting registers code that runs just before that point, guaranteeing the headers can still be modified. Setting headers after next returns can fail silently or throw for streamed responses.
It tells browsers and intermediary caches not to keep a copy of the response. Without it, data such as an account summary might remain in a shared proxy or on a shared computer's browser cache, where another person could read it later. It is a cheap safeguard for any endpoint returning user-specific or sensitive information.
The timeout middleware starts a timer per request and, when it expires, cancels the request's cancellation token. Code that passes that token to database and HTTP calls stops promptly, freeing threads and connections. If the code ignores the token, the timeout cannot actually stop the work, so passing tokens everywhere is what makes timeouts effective.