HTTP headers
suggest changeHTTP headers are name/value pairs sent before the body of every request and response. They carry metadata: content type, authentication, caching rules, cookies, tracing ids and more.
In .NET you work with headers in two places:
- client side with
HttpClient, using theSystem.Net.Http.Headersnamespace - server side with ASP.NET Core (
HttpRequest.Headers,HttpResponse.Headers) or HttpListener
The examples are .NET 10 file-based apps. Save the code as app.cs and run dotnet run app.cs. To keep the output predictable, most examples start a small ASP.NET Core server on localhost:5099 (the #:sdk Microsoft.NET.Sdk.Web line enables it) and then call it with HttpClient in the same program.
Three header collections in HttpClient
HttpClient splits headers into three strongly typed collections. Each one only accepts headers that belong there:
| Collection | Type | Examples |
|---|---|---|
HttpRequestMessage.Headers, HttpClient.DefaultRequestHeaders |
HttpRequestHeaders |
Accept, Authorization, User-Agent, If-None-Match |
HttpResponseMessage.Headers |
HttpResponseHeaders |
ETag, Location, Retry-After, Set-Cookie |
HttpContent.Headers |
HttpContentHeaders |
Content-Type, Content-Length, Content-Encoding, Last-Modified |
Custom headers like X-Api-Key are allowed in the request and response collections.
Sending request headers
Use DefaultRequestHeaders for headers that every request from a client needs, such as an API key or User-Agent. Use HttpRequestMessage.Headers for headers that apply to only one request.
#:sdk Microsoft.NET.Sdk.Web
using System.Net.Http.Headers;
// Tiny local server that echoes back the request headers it receives
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5099");
app.MapGet("/echo", (HttpRequest req) =>
string.Join("\n", req.Headers.OrderBy(h => h.Key).Select(h => $"{h.Key}: {h.Value}")));
await app.StartAsync();
using var client = new HttpClient { BaseAddress = new Uri("http://localhost:5099") };
// Default headers are sent with every request made by this client
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyApp", "1.0"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-Api-Key", "secret-123");
// Per-request headers go on HttpRequestMessage
using var request = new HttpRequestMessage(HttpMethod.Get, "/echo");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "eyJhbGciOi...");
request.Headers.Add("X-Request-Id", Guid.Empty.ToString());
request.Headers.AcceptLanguage.ParseAdd("pl-PL, en;q=0.8");
using var response = await client.SendAsync(request);
Console.WriteLine(await response.Content.ReadAsStringAsync());
await app.StopAsync();
Output:
Accept: application/json
Accept-Language: pl-PL, en; q=0.8
Authorization: Bearer eyJhbGciOi...
Host: localhost:5099
User-Agent: MyApp/1.0
X-Api-Key: secret-123
X-Request-ID: 00000000-0000-0000-0000-000000000000
Things to notice:
- Standard headers have typed properties:
UserAgent,Accept,Authorization,AcceptLanguage,IfNoneMatch,CacheControland others. They build a correctly formatted value for you.ParseAddparses a string into the typed form. Add(name, value)works for any header, including custom ones.Hostis added automatically from the URL.- Header names are case-insensitive. We sent
X-Request-Id, but Kestrel reports it asX-Request-IDbecause that is how ASP.NET Core spells this well-known header. Never write code that depends on the casing of a header name. - The parsed
Accept-Languagevalue comes back asen; q=0.8because .NET re-formats parsed values in a normalized way.
Don't modify DefaultRequestHeaders while requests are running: it isn't thread-safe. Set it once, right after you create the client. For values that change per request (tokens that expire, request ids), set them on HttpRequestMessage or use a DelegatingHandler (shown below).
Content headers and header validation
Content-Type describes the body, so it lives on HttpContent.Headers, not on the request. If you add it to the wrong collection you get an exception. This is the most common header mistake with HttpClient.
using System.Net.Http.Headers;
using System.Text;
using var request = new HttpRequestMessage(HttpMethod.Post, "https://example.com/api");
// Content-Type belongs to the body, so it lives on HttpContent.Headers
request.Content = new StringContent("{\"name\":\"Ann\"}", Encoding.UTF8, "application/json");
Console.WriteLine($"Content-Type: {request.Content.Headers.ContentType}");
Console.WriteLine($"Content-Length: {request.Content.Headers.ContentLength}");
// Change it later via the typed property
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.myapp+json") { CharSet = "utf-8" };
Console.WriteLine($"Content-Type: {request.Content.Headers.ContentType}");
try
{
// Wrong collection: request headers don't accept content headers
request.Headers.Add("Content-Type", "text/plain");
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
// Validation also rejects malformed values for known headers
try
{
request.Headers.Add("Date", "yesterday");
}
catch (FormatException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
// TryAddWithoutValidation skips parsing - use it for non-standard values
bool added = request.Headers.TryAddWithoutValidation("Date", "yesterday");
Console.WriteLine($"Added without validation: {added}, Date = {string.Join(",", request.Headers.GetValues("Date"))}");
Console.WriteLine($"Typed Date property: {request.Headers.Date?.ToString() ?? "(null - could not parse)"}");
Output:
Content-Type: application/json; charset=utf-8
Content-Length: 14
Content-Type: application/vnd.myapp+json; charset=utf-8
Error: Misused header name, 'Content-Type'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
Error: The format of value 'yesterday' is invalid.
Added without validation: True, Date = yesterday
Typed Date property: (null - could not parse)
Add checks that a known header has a valid value. TryAddWithoutValidation stores the string as it is. Use it when a server expects a value that doesn't follow the spec, for example an unusual Authorization scheme or User-Agent. The typed property returns null when it can't parse the stored string.
If you send JSON with PostAsJsonAsync or JsonContent.Create, Content-Type: application/json; charset=utf-8 is set for you. See Sending asynchronous HTTP POST request with JSON body.
Reading response headers
Response headers are split between response.Headers and response.Content.Headers. Use typed properties for standard headers. Use TryGetValues for anything else.
#:sdk Microsoft.NET.Sdk.Web
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5099");
app.MapGet("/data", (HttpResponse res) =>
{
res.Headers.CacheControl = "public, max-age=60";
res.Headers.ETag = "\"v42\"";
res.Headers.Append("X-RateLimit-Remaining", "57");
res.Headers.Append("Set-Cookie", "session=abc; HttpOnly");
res.Headers.Append("Set-Cookie", "theme=dark");
return Results.Text("hello", "text/plain");
});
await app.StartAsync();
using var client = new HttpClient();
using var response = await client.GetAsync("http://localhost:5099/data");
// Typed properties on response headers and content headers
Console.WriteLine($"Status: {(int)response.StatusCode}");
Console.WriteLine($"ETag: {response.Headers.ETag?.Tag}");
Console.WriteLine($"Max-Age: {response.Headers.CacheControl?.MaxAge}");
Console.WriteLine($"Has Date: {response.Headers.Date.HasValue}");
Console.WriteLine($"Content-Type: {response.Content.Headers.ContentType?.MediaType}");
Console.WriteLine($"Length: {response.Content.Headers.ContentLength}");
// Custom headers: TryGetValues returns false instead of throwing when missing
if (response.Headers.TryGetValues("X-RateLimit-Remaining", out var values))
Console.WriteLine($"Remaining: {values.First()}");
Console.WriteLine($"Has X-Missing: {response.Headers.Contains("X-Missing")}");
// A header can appear several times
foreach (string cookie in response.Headers.GetValues("Set-Cookie"))
Console.WriteLine($"Set-Cookie: {cookie}");
// NonValidated: raw strings, no parsing cost (good for logging/proxying)
if (response.Headers.NonValidated.TryGetValues("Cache-Control", out var raw))
Console.WriteLine($"Raw CC: {raw}");
// Enumerate everything: response headers + content headers are separate collections
Console.WriteLine("--- all headers ---");
foreach (var (name, vals) in response.Headers.Concat(response.Content.Headers))
{
if (name == "Date") continue; // changes on every run
Console.WriteLine($"{name}: {string.Join(" | ", vals)}");
}
await app.StopAsync();
Output:
Status: 200
ETag: "v42"
Max-Age: 00:01:00
Has Date: True
Content-Type: text/plain
Length: 5
Remaining: 57
Has X-Missing: False
Set-Cookie: session=abc; HttpOnly
Set-Cookie: theme=dark
Raw CC: public, max-age=60
--- all headers ---
Server: Kestrel
Cache-Control: public, max-age=60
ETag: "v42"
Set-Cookie: session=abc; HttpOnly | theme=dark
X-RateLimit-Remaining: 57
Content-Length: 5
Content-Type: text/plain
Things to know:
GetValues(name)throwsInvalidOperationExceptionwhen the header is missing.TryGetValuesreturnsfalseinstead, so prefer it for optional headers.- A header can have several values. You get them as
IEnumerable<string>. - Looking for
Content-Typeinresponse.Headersfinds nothing. You must checkresponse.Content.Headers. NonValidated(.NET 6+) gives you the raw strings without parsing. It's cheaper and never throws, which makes it a good fit for logging or proxying headers.- To handle cookies automatically, use
HttpClientHandler.CookieContainer(orSocketsHttpHandler.CookieContainer) instead of parsingSet-Cookieyourself.
Conditional requests with ETag
Caching headers let a client skip downloading data it already has. The server sends an ETag (a version id). The client sends it back in If-None-Match. If nothing changed, the server replies 304 Not Modified with an empty body.
#:sdk Microsoft.NET.Sdk.Web
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5099");
const string CurrentETag = "\"v42\"";
app.MapGet("/report", (HttpContext ctx) =>
{
// Server side: compare If-None-Match with the current version
var ifNoneMatch = ctx.Request.GetTypedHeaders().IfNoneMatch;
if (ifNoneMatch.Any(e => e.Tag == CurrentETag))
return Results.StatusCode(304);
ctx.Response.Headers.ETag = CurrentETag;
return Results.Text("large report body");
});
await app.StartAsync();
using var client = new HttpClient();
// First request: no cached copy yet
using var first = await client.GetAsync("http://localhost:5099/report");
var etag = first.Headers.ETag;
Console.WriteLine($"1st: {(int)first.StatusCode}, ETag={etag}, body={await first.Content.ReadAsStringAsync()}");
// Second request: send the ETag back in If-None-Match
using var req = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5099/report");
req.Headers.IfNoneMatch.Add(etag!);
using var second = await client.SendAsync(req);
Console.WriteLine($"2nd: {(int)second.StatusCode} {second.StatusCode}, body length={(await second.Content.ReadAsStringAsync()).Length}");
await app.StopAsync();
Output:
1st: 200, ETag="v42", body=large report body
2nd: 304 NotModified, body length=0
ASP.NET Core and System.Net.Http both define classes named EntityTagHeaderValue, MediaTypeHeaderValue, CacheControlHeaderValue and so on. They live in different namespaces: Microsoft.Net.Http.Headers on the server and System.Net.Http.Headers on the client. If you import both namespaces in one file, you get a CS0104 "ambiguous reference" error. Import only one, or use var or fully qualified names.
HttpClient doesn't cache responses for you. Storing the body and the ETag between calls is up to your code.
Reading and writing headers in ASP.NET Core
On the server, HttpRequest.Headers and HttpResponse.Headers are IHeaderDictionary. They map a header name to StringValues, a struct that holds zero, one or many strings without allocating an array for the common single-value case.
#:sdk Microsoft.NET.Sdk.Web
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://localhost:5099");
// Middleware: add headers to every response
app.Use(async (ctx, next) =>
{
ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
// Headers are sent with the first body byte; OnStarting runs right before that,
// when the endpoint has already chosen the status code
ctx.Response.OnStarting(() =>
{
ctx.Response.Headers["X-Status-Class"] = $"{ctx.Response.StatusCode / 100}xx";
return Task.CompletedTask;
});
await next();
});
app.MapGet("/info", (HttpRequest req, [FromHeader(Name = "X-Tenant")] string? tenant) =>
{
// Indexer returns StringValues; empty (not null) when the header is absent
StringValues agent = req.Headers.UserAgent; // strongly typed property
StringValues raw = req.Headers["x-tags"]; // names are case-insensitive
string[] tags = req.Headers.GetCommaSeparatedValues("X-Tags");
string? missing = req.Headers["X-Nope"].FirstOrDefault();
// Typed, parsed view of standard headers
var typed = req.GetTypedHeaders();
var accept = typed.Accept.OrderByDescending(a => a.Quality ?? 1).Select(a => a.MediaType.ToString());
return $"""
tenant = {tenant}
agent = {agent}
raw = {raw.Count} value: "{raw}"
tags = {tags.Length} values: {string.Join(" / ", tags)}
missing = {missing ?? "(null)"}
accept = {string.Join(" > ", accept)}
""";
});
await app.StartAsync();
using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5099/info");
request.Headers.Add("X-Tenant", "acme");
request.Headers.Add("User-Agent", "curl/8.10");
request.Headers.Add("X-Tags", new[] { "red", "blue" });
request.Headers.Add(HeaderNames.Accept, "text/html;q=0.5, application/json");
using var response = await client.SendAsync(request);
Console.WriteLine(await response.Content.ReadAsStringAsync());
Console.WriteLine($"X-Content-Type-Options: {response.Headers.GetValues("X-Content-Type-Options").Single()}");
Console.WriteLine($"X-Status-Class: {response.Headers.GetValues("X-Status-Class").Single()}");
await app.StopAsync();
Output:
tenant = acme
agent = curl/8.10
raw = 1 value: "red, blue"
tags = 2 values: red / blue
missing = (null)
accept = application/json > text/html
X-Content-Type-Options: nosniff
X-Status-Class: 2xx
What this shows:
[FromHeader(Name = "...")]binds a header straight to an endpoint parameter. It works in minimal APIs and in controllers.- The indexer
Headers["name"]never throws. A missing header givesStringValues.Empty, so.FirstOrDefault()returnsnull. IHeaderDictionaryhas typed properties for well-known headers (UserAgent,Authorization,CacheControl,ETag...). They save you from typos in header names. Constants such asHeaderNames.Acceptare also available.- When you
Addseveral values on the client,HttpClientjoins them into one comma-separated header line. The server sees one value,"red, blue".GetCommaSeparatedValuessplits it correctly and respects quoted strings. GetTypedHeaders()parses standard headers into objects. Here we sortAcceptby itsqquality factor.OnStartingcallbacks run just before the headers are sent. That's the last moment you can add a header, and by then the final status code is known.
Headers can't change after the response has started
HTTP sends headers before the body. As soon as you write the first byte of the body, the headers are on the wire and the collection becomes read-only.
The next example also shows a DelegatingHandler that adds headers to every outgoing request. Use this pattern together with IHttpClientFactory for correlation ids or tokens that need refreshing:
#:sdk Microsoft.NET.Sdk.Web
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
// Named client whose handler pipeline adds headers to every request
builder.Services.AddTransient<HeaderHandler>();
builder.Services.AddHttpClient("api", c =>
{
c.BaseAddress = new Uri("http://localhost:5099");
c.DefaultRequestHeaders.Authorization = new("Bearer", "token-from-config");
}).AddHttpMessageHandler<HeaderHandler>();
var app = builder.Build();
app.Urls.Add("http://localhost:5099");
app.MapGet("/whoami", (HttpRequest req) =>
$"correlation={req.Headers["X-Correlation-Id"]}, auth={req.Headers.Authorization}");
app.MapGet("/late", async (HttpResponse res) =>
{
await res.WriteAsync("body first...");
try
{
res.Headers["X-Too-Late"] = "1"; // headers already went out with the body
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Server error: {ex.Message}");
}
});
await app.StartAsync();
var client = app.Services.GetRequiredService<IHttpClientFactory>().CreateClient("api");
Console.WriteLine(await client.GetStringAsync("/whoami"));
Console.WriteLine(await client.GetStringAsync("/whoami"));
Console.WriteLine(await client.GetStringAsync("/late"));
await app.StopAsync();
class HeaderHandler : DelegatingHandler
{
private int _counter;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
// Don't overwrite a value the caller set explicitly
if (!request.Headers.Contains("X-Correlation-Id"))
request.Headers.Add("X-Correlation-Id", $"req-{Interlocked.Increment(ref _counter)}");
return base.SendAsync(request, ct);
}
}
Output:
correlation=req-1, auth=Bearer token-from-config
correlation=req-2, auth=Bearer token-from-config
Server error: Headers are read-only, response has already started.
body first...
To set a header that depends on work done later in the request, set it before writing the body, or register Response.OnStarting.
Common pitfalls
- Wrong collection:
Content-Type,Content-Length,Content-Disposition,ExpiresandLast-Modifiedare content headers. Set them onHttpContent.Headers. - Duplicates: calling
Addtwice for the same name appends a second value instead of replacing the first. CallRemove(name)first to replace a value. - Case: header names are case-insensitive in HTTP/1.1 and always lowercase on the wire in HTTP/2 and HTTP/3. The built-in collections already compare names case-insensitively. Do the same in your own dictionaries with
StringComparer.OrdinalIgnoreCase. - Non-ASCII values: header values should be ASCII. To send other characters, encode them (for example with
Uri.EscapeDataString) or setSocketsHttpHandler.RequestHeaderEncodingSelector. - Secrets in logs:
Authorization,Cookieand API key headers end up in logs if you dump all headers. Redact them. Recent versions of theIHttpClientFactorylogging redact header values by default. Configure which ones withRedactLoggedHeaders. - Forwarded headers: behind a reverse proxy, the client IP and scheme arrive in
X-Forwarded-ForandX-Forwarded-Proto. Useapp.UseForwardedHeaders()rather than reading them by hand. Only trust them from known proxies.
Related: CORS relies entirely on Access-Control-* headers, and TLS and HTTPS covers secure connections.