Repository navigation
Description
Description
Since .NET 10, SocketsHttpHandler throws a NullReferenceException from HttpConnectionPool.HandleAltSvc when an HTTPS response has an Alt-Svc header that is empty (Alt-Svc:) or contains only separators (Alt-Svc: ,). The exception escapes HttpClient.SendAsync as is (it is not wrapped in HttpRequestException), and the request fails.
The request itself is plain HTTP/1.1, and no HTTP/3 connection is ever attempted. Alt-Svc is still processed on every HTTPS response whenever HTTP/3 support is enabled, which is the default.
We hit this in production against a third-party server that answers with a 302 and an empty Alt-Svc header. The status code doesn't matter: a 200 with an empty Alt-Svc fails the same way. Framework frames of the production stack trace:
System.NullReferenceException
at System.Net.Http.HttpConnectionPool.HandleAltSvc(IEnumerable`1 altSvcHeaderValues, Nullable`1 responseAge) in /src/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/HttpConnectionPool.Http3.cs:line 679
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in /src/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ConnectionPool/HttpConnectionPool.cs:line 495
at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) in /src/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs:line 165
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) in /src/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/RedirectHandler.cs:line 29
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken) in /src/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs:line 523
Reproduction Steps
This is a self-contained console app. It starts a small HTTPS/1.1 server on loopback with a self-signed certificate, which answers with a given Alt-Svc value. The client is a default HttpClientHandler with certificate validation disabled. No external network access or packages are needed.
AltSvcNreRepro.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>Program.cs:
// Minimal repro: SocketsHttpHandler throws NullReferenceException in HttpConnectionPool.HandleAltSvc
// when an HTTPS response carries an empty "Alt-Svc:" header (.NET 10 regression from dotnet/runtime#114528).
//
// A tiny HTTPS/1.1 server on localhost answers every request with the given Alt-Svc header value.
// Usage: dotnet run -f net10.0 [-- --disable-http3]
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
if (args.Contains("--disable-http3"))
{
// Proposed workaround: must run before the first SocketsHttpHandler/HttpClientHandler is created.
AppContext.SetSwitch("System.Net.SocketsHttpHandler.Http3Support", false);
}
Console.WriteLine($"Runtime: {RuntimeInformation.FrameworkDescription}, Http3Support switch: " +
(AppContext.TryGetSwitch("System.Net.SocketsHttpHandler.Http3Support", out bool on) ? on.ToString() : "default"));
(string Name, string Status, string? AltSvc)[] cases =
[
("302 + empty Alt-Svc", "302 Found", ""),
("200 + empty Alt-Svc", "200 OK", ""),
("200 + Alt-Svc: ','", "200 OK", ","),
("200 + no Alt-Svc", "200 OK", null),
("200 + Alt-Svc: clear", "200 OK", "clear"),
("200 + Alt-Svc: h3=\":443\"", "200 OK", "h3=\":443\""),
];
using X509Certificate2 cert = CreateSelfSignedCert();
foreach (var (name, status, altSvc) in cases)
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
Task server = ServeAsync(listener, cert, status, altSvc, port);
// Default HttpClientHandler settings: HTTP/1.1 request, auto-redirect on.
using var client = new HttpClient(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
});
try
{
using HttpResponseMessage response = await client.GetAsync($"https://localhost:{port}/click");
Console.WriteLine($" OK {name,-32} -> {(int)response.StatusCode}");
}
catch (Exception ex)
{
Console.WriteLine($" FAIL {name,-32} -> {ex.GetType().Name}");
Console.WriteLine(" " + ex.StackTrace?.Split('\n')[0].Trim());
}
listener.Stop();
await server.ContinueWith(_ => { });
}
static async Task ServeAsync(TcpListener listener, X509Certificate2 cert, string status, string? altSvc, int port)
{
while (true)
{
using TcpClient tcp = await listener.AcceptTcpClientAsync();
await using var ssl = new SslStream(tcp.GetStream());
await ssl.AuthenticateAsServerAsync(new SslServerAuthenticationOptions
{
ServerCertificate = cert,
ApplicationProtocols = [SslApplicationProtocol.Http11],
});
// Read the request head; we don't care about its content.
var buffer = new byte[8192];
var head = new StringBuilder();
while (!head.ToString().Contains("\r\n\r\n"))
{
int read = await ssl.ReadAsync(buffer);
if (read == 0) break;
head.Append(Encoding.ASCII.GetString(buffer, 0, read));
}
// The redirect target answers 200 with no Alt-Svc, so a 302 case only fails on the first hop.
bool isRedirectTarget = head.ToString().StartsWith("GET /landing");
var response = new StringBuilder();
response.Append($"HTTP/1.1 {(isRedirectTarget ? "200 OK" : status)}\r\n");
if (!isRedirectTarget && status.StartsWith("302")) response.Append($"Location: https://localhost:{port}/landing\r\n");
if (!isRedirectTarget && altSvc is not null) response.Append($"Alt-Svc: {altSvc}\r\n");
response.Append("Content-Length: 0\r\nConnection: close\r\n\r\n");
await ssl.WriteAsync(Encoding.ASCII.GetBytes(response.ToString()));
}
}
static X509Certificate2 CreateSelfSignedCert()
{
using var rsa = RSA.Create(2048);
var request = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
var san = new SubjectAlternativeNameBuilder();
san.AddDnsName("localhost");
request.CertificateExtensions.Add(san.Build());
using X509Certificate2 ephemeral = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
// Round-trip through PFX so SChannel on Windows can use the private key.
#pragma warning disable SYSLIB0057
return new X509Certificate2(ephemeral.Export(X509ContentType.Pfx));
#pragma warning restore SYSLIB0057
}To run it, use dotnet run -f net10.0. Add -f net9.0 or -f net8.0 to compare versions, and append -- --disable-http3 to try the workaround.
Expected behavior
As in .NET 8 and 9, an empty or unparsable Alt-Svc value is ignored and the request succeeds.
Actual behavior
Runtime: .NET 10.0.3, Http3Support switch: default
FAIL 302 + empty Alt-Svc -> NullReferenceException
at System.Net.Http.HttpConnectionPool.HandleAltSvc(IEnumerable`1 altSvcHeaderValues, Nullable`1 responseAge)
FAIL 200 + empty Alt-Svc -> NullReferenceException
at System.Net.Http.HttpConnectionPool.HandleAltSvc(IEnumerable`1 altSvcHeaderValues, Nullable`1 responseAge)
FAIL 200 + Alt-Svc: ',' -> NullReferenceException
at System.Net.Http.HttpConnectionPool.HandleAltSvc(IEnumerable`1 altSvcHeaderValues, Nullable`1 responseAge)
OK 200 + no Alt-Svc -> 200
OK 200 + Alt-Svc: clear -> 200
OK 200 + Alt-Svc: h3=":443" -> 200
On .NET 9.0.13 and 8.0.32, all six cases print OK ... -> 200.
Regression?
Yes. It works in .NET 8 and 9, and is broken from 10.0.0 on. It was introduced by #114528 ("[H/3] Clean up and fix Alt-Svc handling"), which replaced the null check on the parsed value with a Debug.Assert:
if (AltSvcHeaderParser.Parser.TryParseValue(altSvcHeaderValue, null, ref parseIdx, out object? parsedValue))
{
- var value = (AltSvcHeaderValue?)parsedValue;
+ Debug.Assert(parsedValue is not null);
+
+ var value = (AltSvcHeaderValue)parsedValue;
...
- if (nextAuthority == null && value != null && value.AlpnProtocolName == "h3")
+ // Do not process the Alt-Svc header if we've already found a valid h3 authority before, but continue looking for potential "clear".
+ if (nextAuthority is not null || value.AlpnProtocolName != "h3")This null check was added on purpose in 2020, for exactly this case: see this review comment on #33646 ("parsedValue could be null if altSvcHeaderValue is null or empty"). The test requested back then, #33699 ("Add test for HttpConnectionPool with an empty/null AltSvcHeaderValue"), is still open, so nothing caught its removal.
Known Workarounds
Disable HTTP/3 support. This also turns off Alt-Svc processing. Any of these works:
AppContext.SetSwitch("System.Net.SocketsHttpHandler.Http3Support", false);, called before the firstSocketsHttpHandler/HttpClientHandleris created.DOTNET_SYSTEM_NET_HTTP_SOCKETSHTTPHANDLER_HTTP3SUPPORT=false<RuntimeHostConfigurationOption Include="System.Net.SocketsHttpHandler.Http3Support" Value="false" />in the project file.
Configuration
No response
Other information
AltSvcHeaderParser is created with supportsMultipleValues: true. For such parsers, BaseHeaderParser.TryParseValue returns true with parsedValue == null in two cases: when the value is empty (BaseHeaderParser.cs L39-L42), and when it contains only separators or whitespace (L53-L60). HandleAltSvc then dereferences that null value at HttpConnectionPool.Http3.cs L679:
if (AltSvcHeaderParser.Parser.TryParseValue(altSvcHeaderValue, null, ref parseIdx, out object? parsedValue))
{
Debug.Assert(parsedValue is not null); // fires in Debug builds, no-op in Release
var value = (AltSvcHeaderValue)parsedValue;
...
if (nextAuthority is not null || value.AlpnProtocolName != "h3") // line 679: NRESuggested fix. Skip null values instead of asserting:
if (AltSvcHeaderParser.Parser.TryParseValue(altSvcHeaderValue, null, ref parseIdx, out object? parsedValue) &&
parsedValue is AltSvcHeaderValue value)
{Adding the functional test from #33699 would prevent this from coming back: an HTTPS response with an empty Alt-Svc value (and one with only ,) should succeed.
Activity
dotnet-policy-service commentedon Oct 22, 2026
Tagging subscribers to this area: @karelz, @dotnet/ncl
See info in area-owners.md if you want to be subscribed.
Ignore empty Alt-Svc values instead of throwing NullReferenceException