HttpRequest HTTP 2.0

HttpRequest Http 2.0

我正在尝试发出 HTTP/2.0 请求,但无法正常工作。根据这个和其他帖子 .NET > 3.0 应该支持它,但我无法让它工作。

       Debug.WriteLine("Version:"+ Environment.Version.ToString());

        var client = new HttpClient();

        var req = new HttpRequestMessage(HttpMethod.Get,"https://http2.akamai.com/demo")
        {
            Version = new Version(2, 0)
        };

        var x = await client.SendAsync(req);

上面的代码生成:

Version:4.0.30319.42000
Exception thrown: 'System.ArgumentException' in mscorlib.dll
An exception of type 'System.ArgumentException' occurred in mscorlib.dll but was not handled in user code
Only HTTP/1.0 and HTTP/1.1 version requests are currently supported.

您没有使用 .NET-Core.

您使用的版本 - 4.0.30319.42000 - 对应于 .NET Framework 4.6+,而不是 .NET core。

来自How to: Determine which .NET Framework versions are installed

The common language runtime (CLR), which manages and executes your app's code. A single CLR version typically supports multiple .NET Framework versions. For example, CLR version 4.0.30319.xxxxx where xxxxx is less than 42000, supports .NET Framework versions 4 through 4.5.2. CLR version greater than or equal to 4.0.30319.42000 supports .NET Framework versions starting with .NET Framework 4.6.

.NET Framework 仅支持 Http 版本 1/1.1,但是这个问题 有一些解决方法。

我已经测试了您的代码,它适用于 .NET core 3.1 和 .NET 6。Demo in .NET 6