How to send a header with non-standard casing (Content-type, Content-length) from HttpClient in .NET 10
HttpClient on .NET 10 and .NET 11 rewrites known header names like Content-type to their canonical casing, even through TryAddWithoutValidation. Raw socket captures show what it changes, what it leaves alone, and how to send multipart part headers byte-for-byte with a small custom HttpContent.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
On .NET 10 and .NET 11, HttpClient writes every known header (Content-Type, Content-Length, User-Agent and the rest of its built-in list) with its canonical casing, no matter how you spelled it. TryAddWithoutValidation("Content-type", ...) skips value parsing, not name normalization. Custom header names (x-Custom-HEADER) keep your casing. If a legacy server insists on Content-type inside multipart part headers, the supported fix is to write the multipart body yourself with a small HttpContent subclass, because HttpClient then never sees those lines as headers. For the request’s own top-level Content-Length, there is no reliable way: even a reflection hack produces a duplicate or a chunked request.
Everything below was checked by capturing the raw request bytes on a local TcpListener, on .NET 10.0.14 (SDK 10.0.403) and .NET 11.0.0 (SDK 11.0.100), macOS arm64, HTTP/1.1 over plain TCP. Both runtimes produced byte-identical output for every case.
Where this comes up
The case that prompted this post is a Stack Overflow question about a legacy EDI upload to a shipping supplier. The supplier’s endpoint expects multipart parts that look exactly like this:
--BOUNDARY
Content-type: application/x-ups-binary
Content-length: 7
PAYLOAD
--BOUNDARY--
The asker reports that on .NET Framework, removing the typed header and re-adding it with TryAddWithoutValidation kept the lowercase t and l, and that the same code on .NET 10 silently sends Content-Type and Content-Length. That .NET Framework behavior is the asker’s report; it was not re-tested for this post, since .NET Framework does not run on the machine used here.
HTTP says header field names are case-insensitive (RFC 9110, section 5.1), and MIME part headers follow the same rule. A server that rejects Content-Type is broken. But “fix your server” is not an answer when the server belongs to someone else, so the useful question is what HttpClient will and will not let you control.
What HttpClient actually puts on the wire
The test harness is a console app that opens a TcpListener on 127.0.0.1, points an HttpClient at it, and prints the exact bytes it receives with \r\n made visible:
// .NET 10 / .NET 11, C# 14
using System.Net;
using System.Net.Sockets;
using System.Text;
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
var url = $"http://127.0.0.1:{port}/upload";
using var client = new HttpClient();
async Task Show(string title, HttpRequestMessage req)
{
var serverTask = Capture(listener);
using var resp = await client.SendAsync(req);
Console.WriteLine($"===== {title} =====");
Console.WriteLine((await serverTask).Replace("\r\n", "\\r\\n\n"));
}
static async Task<string> Capture(TcpListener l)
{
using var sock = await l.AcceptTcpClientAsync();
var s = sock.GetStream();
var buf = new byte[65536];
var ms = new MemoryStream();
int headerEnd = -1;
while (headerEnd < 0)
{
int n = await s.ReadAsync(buf);
if (n == 0) break;
ms.Write(buf, 0, n);
headerEnd = Encoding.ASCII.GetString(ms.ToArray()).IndexOf("\r\n\r\n");
}
var text = Encoding.ASCII.GetString(ms.ToArray());
var head = text[..headerEnd];
var lenLine = head.Split("\r\n").FirstOrDefault(
h => h.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase));
bool chunked = head.Contains("Transfer-Encoding: chunked", StringComparison.OrdinalIgnoreCase);
while (true)
{
text = Encoding.ASCII.GetString(ms.ToArray());
if (lenLine is not null && text.Length >= headerEnd + 4 + int.Parse(lenLine.Split(':')[1])) break;
if (chunked && text.EndsWith("0\r\n\r\n")) break;
int n = await s.ReadAsync(buf);
if (n == 0) break;
ms.Write(buf, 0, n);
}
await s.WriteAsync("HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"u8.ToArray());
return text;
}
Top-level request headers
var req = new HttpRequestMessage(HttpMethod.Post, url);
req.Headers.TryAddWithoutValidation("user-AGENT", "edi-client/1.0");
req.Headers.TryAddWithoutValidation("x-Custom-HEADER", "kept");
req.Content = new ByteArrayContent("hi"u8.ToArray());
req.Content.Headers.TryAddWithoutValidation("Content-type", "application/x-ups-binary");
await Show("top-level headers via TryAddWithoutValidation", req);
Captured bytes, identical on 10.0.14 and 11.0.0:
POST /upload HTTP/1.1\r\n
Host: 127.0.0.1:59315\r\n
User-Agent: edi-client/1.0\r\n
x-Custom-HEADER: kept\r\n
Content-Type: application/x-ups-binary\r\n
Content-Length: 2\r\n
\r\n
hi
user-AGENT became User-Agent, Content-type became Content-Type, and x-Custom-HEADER went out exactly as written. The value of Content-type was not touched: TryAddWithoutValidation really does skip value validation. It just does not skip the name lookup.
Multipart part headers (the Stack Overflow code)
var data = "PAYLOAD";
var form = new MultipartFormDataContent("BOUNDARY");
var content = new StringContent(data + "\r\n");
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-type", "application/x-ups-binary");
content.Headers.Remove("Content-Length");
content.Headers.TryAddWithoutValidation("Content-length", data.Length.ToString());
form.Add(content);
await Show("multipart part headers", new(HttpMethod.Post, url) { Content = form });
POST /upload HTTP/1.1\r\n
Host: 127.0.0.1:59315\r\n
Content-Type: multipart/form-data; boundary="BOUNDARY"\r\n
Content-Length: 130\r\n
\r\n
--BOUNDARY\r\n
Content-Type: application/x-ups-binary\r\n
Content-Length: 7\r\n
Content-Disposition: form-data\r\n
\r\n
PAYLOAD\r\n
\r\n
--BOUNDARY--\r\n
Three things a picky legacy server might choke on, not one:
- Both part headers are re-cased.
MultipartFormDataContent.AddappendedContent-Disposition: form-data, which the expected format does not have.- The boundary parameter is quoted:
boundary="BOUNDARY". TheMultipartContentconstructor wraps any boundary that does not already start with"in quotes. That is valid per RFC 2046, but hand-rolled parsers often compare the raw string.
There is also a bug in the original snippet, unrelated to casing: the part body is data + "\r\n" (9 bytes) while Content-length claims data.Length (7). The \r\n before the next boundary already belongs to the delimiter, so the extra one ends up inside the part body.
Why the casing changes: HeaderDescriptor and KnownHeaders
Every header name in System.Net.Http is resolved to a HeaderDescriptor before it is stored. HeaderDescriptor.TryGet first calls KnownHeaders.TryGetKnownHeader(headerName), which matches case-insensitively. On a hit, the descriptor wraps the shared KnownHeader object and throws away your string. Only names that are not on the known list are stored as the string you passed. The descriptor’s Name property returns KnownHeader.Name for known headers, which is the canonical spelling.
The public TryAddWithoutValidation(string, string) goes through that same lookup. Its “without validation” part refers to the value parser, which is why application/x-ups-binary survived unchanged while the name did not.
The two writers then use that canonical form:
SocketsHttpHandler’s HTTP/1.1 connection, inHttpConnection.WriteHeaderCollection, writesknownHeader.AsciiBytesWithColonSpace(a precomputed"Content-Type: "byte array) for known headers andheader.Key.Namefor custom ones.MultipartContent.SerializeHeadersToStreamenumeratescontent.Headers.NonValidatedand writes each key, which again is the descriptor name.
So there is no public switch. It is not a regression in .NET 10 or 11 either: the captured output did not change between 10.0.14 and 11.0.0.
Fix: write the multipart body yourself
If the strict casing is only required inside the multipart body, which is the common legacy EDI case, skip MultipartFormDataContent entirely. Part headers are just bytes inside the request body. If your own HttpContent produces those bytes, HttpClient never parses them as headers and has nothing to normalize.
- Create an
HttpContentsubclass that holds a list of parts, each part being an ordered list of raw(name, value)pairs plus a body. - Set the outer
Content-TypewithTryAddWithoutValidationso the boundary is not re-quoted. - Serialize
--boundary\r\n, eachname: value\r\nexactly as given, a blank line, the body,\r\n, and finish with--boundary--\r\n. - Override
TryComputeLengthso the request goes out with aContent-Lengthinstead ofTransfer-Encoding: chunked, which old servers frequently mishandle.
// .NET 10 / .NET 11, C# 14
using System.Net;
using System.Text;
sealed class RawMultipartContent : HttpContent
{
private readonly string _boundary;
private readonly List<(IReadOnlyList<(string Name, string Value)> Headers, byte[] Body)> _parts = [];
private byte[]? _bytes;
public RawMultipartContent(string boundary)
{
_boundary = boundary;
// Value only, so the parser cannot reformat it; the name is still "Content-Type".
Headers.TryAddWithoutValidation("Content-Type", $"multipart/form-data; boundary={boundary}");
}
public void AddPart(IReadOnlyList<(string Name, string Value)> headers, byte[] body)
{
_parts.Add((headers, body));
_bytes = null;
}
private byte[] Bytes => _bytes ??= Build();
private byte[] Build()
{
var ms = new MemoryStream();
void W(string s) { var b = Encoding.ASCII.GetBytes(s); ms.Write(b); }
foreach (var (headers, body) in _parts)
{
W($"--{_boundary}\r\n");
foreach (var (name, value) in headers) W($"{name}: {value}\r\n");
W("\r\n");
ms.Write(body);
W("\r\n");
}
W($"--{_boundary}--\r\n");
return ms.ToArray();
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context)
=> stream.WriteAsync(Bytes).AsTask();
protected override bool TryComputeLength(out long length)
{
length = Bytes.Length;
return true;
}
}
Usage:
var payload = Encoding.ASCII.GetBytes("PAYLOAD");
var body = new RawMultipartContent("BOUNDARY");
body.AddPart(
[("Content-type", "application/x-ups-binary"), ("Content-length", payload.Length.ToString())],
payload);
using var response = await client.PostAsync(url, body);
Captured on both runtimes:
POST /upload HTTP/1.1\r\n
Host: 127.0.0.1:59400\r\n
Content-Type: multipart/form-data; boundary=BOUNDARY\r\n
Content-Length: 96\r\n
\r\n
--BOUNDARY\r\n
Content-type: application/x-ups-binary\r\n
Content-length: 7\r\n
\r\n
PAYLOAD\r\n
--BOUNDARY--\r\n
Part headers are byte-for-byte what you passed, there is no injected Content-Disposition, the boundary is unquoted, and Content-length matches the 7 payload bytes. The outer Content-Type and Content-Length are still canonical, which is fine for any server that only cares about the part headers.
A few notes on this class:
- It buffers the whole body, which is right for EDI-sized payloads. For large files, write the header bytes, then copy the file stream inside
SerializeToStreamAsync, and compute the length from the header byte count plusFileInfo.Length. - Because you now own the format, you also own its rules: the boundary must not occur inside any body, and header names and values must not contain
\ror\n. Validate them if any of that comes from user input, or you have built a header injection hole. - It works the same through
IHttpClientFactoryand typed clients, since it is just anHttpContent. That also makes it easy to assert on in tests, along the lines of unit testing code that uses HttpClient with a fake handler that readsrequest.Content.ReadAsStringAsync().
The reflection workaround, and where it breaks
The accepted Stack Overflow answer constructs a HeaderDescriptor directly through its internal (string headerName, bool customHeader) constructor, then calls the internal HttpHeaders.TryAddWithoutValidation(HeaderDescriptor, string) overload. That bypasses the KnownHeaders lookup, so the descriptor holds your string and both writers treat it as a custom header:
// .NET 10 / .NET 11. Unsupported: depends on System.Net.Http internals.
using System.Net.Http.Headers;
using System.Reflection;
static class VerbatimHeaders
{
private static readonly Type DescriptorType =
typeof(HttpHeaders).Assembly.GetType("System.Net.Http.Headers.HeaderDescriptor", throwOnError: true)!;
private static readonly MethodInfo TryAdd = typeof(HttpHeaders).GetMethod(
"TryAddWithoutValidation",
BindingFlags.Instance | BindingFlags.NonPublic,
[DescriptorType, typeof(string)])
?? throw new MissingMethodException("HttpHeaders.TryAddWithoutValidation(HeaderDescriptor, string)");
public static void AddVerbatim(this HttpHeaders headers, string name, string value)
{
var descriptor = Activator.CreateInstance(DescriptorType,
BindingFlags.Instance | BindingFlags.NonPublic, null, [name, false], null);
if (!(bool)TryAdd.Invoke(headers, [descriptor!, value])!)
throw new InvalidOperationException($"{name} was rejected");
}
}
On 10.0.14 and 11.0.0 this does work for Content-type, both on the request and on a multipart part:
POST /upload HTTP/1.1\r\n
Host: 127.0.0.1:59315\r\n
Content-type: application/x-ups-binary\r\n
Content-Length: 2\r\n
\r\n
hi
It falls apart on the request’s own Content-length. HttpContentHeaders.ContentLength is computed lazily: when the handler enumerates the headers and finds no stored value under the known Content-Length descriptor, it asks the content for its length and adds a canonical header. Your verbatim header is stored under a different descriptor, so the request goes out with both:
POST /upload HTTP/1.1\r\n
Host: 127.0.0.1:59352\r\n
Content-length: 2\r\n
Content-Length: 2\r\n
\r\n
hi
Setting Content.Headers.ContentLength = null first stops the computed value, but then SocketsHttpHandler sees a request body with no length and switches to chunked encoding:
POST /upload HTTP/1.1\r\n
Host: 127.0.0.1:59364\r\n
Transfer-Encoding: chunked\r\n
Content-length: 2\r\n
\r\n
2\r\n
hi\r\n
0\r\n
\r\n
Both outputs are malformed. A message with both Transfer-Encoding and Content-Length is exactly the shape RFC 9112, section 6.3 calls out as a request smuggling risk, and well-behaved proxies will reject it. Do not ship either. Inside a multipart part this problem does not exist (ByteArrayContent only computes its length when someone reads ContentLength, and MultipartContent does not), which is why the part version worked.
Beyond that, the usual reflection caveats apply. The constructor and the internal overload are private implementation details that can be renamed in any servicing release, the code breaks under trimming and Native AOT without extra annotations, and the cost of MethodInfo.Invoke on every call is real (see the UnsafeAccessor vs reflection numbers for how much). If you must use it, keep the MissingMethodException guard so a runtime update fails loudly at startup instead of silently sending canonical headers again.
Gotchas worth knowing before you debug a server
- HTTP/2 and HTTP/3 make this moot. RFC 9113, section 8.2 requires lowercase field names on the wire, and HPACK/QPACK encode them that way. If the endpoint negotiates HTTP/2, the server never sees your casing at all. Casing only matters on HTTP/1.1, which is what legacy EDI endpoints speak.
- Proxies and gateways may normalize too. A corporate proxy, an API gateway, or a load balancer that terminates and re-emits HTTP/1.1 can rewrite names on the way through. Capture at the server, not just at the client.
- Custom names are already safe. Anything not on the known list,
X-Api-keyorSOAPAction-style names thatHttpClientdoes not recognize, keeps your exact casing through the plain public API. You only need any of this for the built-in names. - A trailing CRLF in the body is not the delimiter. As seen in the original snippet, the
\r\nthat precedes--BOUNDARYbelongs to the delimiter. Adding your own means the part body gets two extra bytes and the declared length no longer matches. - Raw sockets are the last resort. If the top-level
Content-Lengthtruly must beContent-length,HttpClientcannot do it reliably. You would have to write the HTTP/1.1 request yourself over aTcpClient(plusSslStreamfor HTTPS), which also means owning redirects, keep-alive, and response parsing. Before going there, ask the supplier; servers that reject canonicalContent-Lengthare rare enough that the multipart-only requirement is far more likely.
If the server answers malformed requests by closing the connection, the client symptom is usually HttpIOException: The response ended prematurely rather than a clean 400, so a raw capture like the one above is the fastest way to see what was actually sent. For deciding where RawMultipartContent lives in a larger app, the HttpClient vs IHttpClientFactory vs Refit comparison covers the trade-offs, and if the same endpoint is later moved to HTTP/2, the HTTP/2 stream reset fix covers the errors that tend to show up next.
Sources
- Stack Overflow: Non-standard header in HttpClient (question and accepted reflection answer)
HeaderDescriptor.cs, dotnet/runtime release/10.0HttpConnection.cs(WriteHeaderCollection), dotnet/runtime release/10.0MultipartContent.cs, dotnet/runtime release/10.0HttpContentHeaders.cs(lazyContentLength), dotnet/runtime release/10.0- HttpHeaders.TryAddWithoutValidation on MS Learn
- RFC 9110 section 5.1, RFC 9112 section 6.3, RFC 9113 section 8.2, RFC 2046 section 5.1.1
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.