门户网站建设 总结,物流网站系统php源码,下载谷歌浏览器并安装,建筑模板尺寸是多少咨询区 Justin Lessard#xff1a;我的一个项目需要支持 Http 2.0 进行数据的收发#xff0c;目前用的项目版本是 .NET Core 2.2#xff0c;我选型了 HttpClient#xff0c;但是我发现一个问题#xff0c;在生产环境中的程序返回的 response 版本一直都是 Http 1.1#x… 咨询区 Justin Lessard我的一个项目需要支持 Http 2.0 进行数据的收发目前用的项目版本是 .NET Core 2.2我选型了 HttpClient但是我发现一个问题在生产环境中的程序返回的 response 版本一直都是 Http 1.1请问大家我该如何正确配置参考代码
using (var client new HttpClient())
{using (var request new HttpRequestMessage(new HttpMethod(GET),https://duckduckgo.com/)){request.Version new Version(2, 0);var response await client.SendAsync(request);Console.WriteLine(response.Version);}
}回答区 Panagiotis Kanavos你应该用的是 .Net Core 3 之前的版本因为在 3.0 中已经提供了 Http 2 的支持下面的代码将会解决你的问题并输出 2.0.class Program{static void Main(string[] args){Test();Console.ReadLine();}static async void Test(){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);var version x.Version;Console.WriteLine(version);}}undrivendev在 .NET 2.1 中HttpClient 底层采用的是 SocketsHttpClientHandler 这种新一代的 handler 是不支持 Http/2 的所以这是你一直看不到 1.1 的原因。另外现在都不推荐直接用 HttpClient最佳模式是改成 HttpClientFactory可以参考官方的使用案例https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?viewaspnetcore-5.0下面是一个将 HttpClient 注册为 typeClient 并且配置成 http/2 的例子。
public void ConfigureServices(IServiceCollection services)
{
...services.AddHttpClientExampleService().ConfigureHttpClient((client) {client.DefaultRequestVersion new Version(2, 0);});
...
}点评区 其实网络上有很多关于描述 HttpClient 的弊端比如无法有效的感知 url 的 DNS 变更network 上的 4min 问题大家还是有必要明白这些问题的解决方案 HttpClientFactory从这一系列例子上.NET Core 3 开始已经是一本相对功能齐全稳定的版本了项目能升级到3.0的尽快升级。