.net7 htt2.0 htt3.0

服务器端

代码配置

 var builder = WebApplication.CreateBuilder(args);

            builder.WebHost.ConfigureKestrel((context, options) =>
            {
                options.ListenAnyIP(44319, listenOptions =>
                {
            // 服务器端支持 http2 listenOptions.Protocols
= HttpProtocols.Http1AndHttp2; listenOptions.UseHttps(); }); });

或者在配置文件配置

"Kestrel": {
    "EndpointDefaults": {
      "Protocols": "Http1AndHttp2"
    }
  }

客户端

 services
            .AddHttpClient(Options.DefaultName)
            .ConfigureHttpClient((httpClient) =>
            {
                httpClient.DefaultRequestVersion = HttpVersion.Version20;
                httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower;
            });

注入 IHttpClientFactory httpClientFactory

通过 HttpClient myHttpClient  =  httpClientFactory.CreateClient(); 

或者通过以下方式直接new

        private static async Task Main(string[] args)
        {
       // 设置请求 策略和请求 http协议版本  HttpClient myHttpClient
= new HttpClient { DefaultRequestVersion = HttpVersion.Version20, DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower }; string requestUrl = "https://localhost:44319/api/abp/a/zzz"; try { Console.WriteLine($"GET {requestUrl}."); HttpResponseMessage response = await myHttpClient.GetAsync(requestUrl); response.EnsureSuccessStatusCode(); Console.WriteLine($"Response HttpVersion: {response.Version}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Response Body Length is: {responseBody.Length}"); Console.WriteLine($"------------Response Body------------"); Console.WriteLine(responseBody); Console.WriteLine($"------------End of Response Body------------"); } catch (HttpRequestException e) { Console.WriteLine($"HttpRequestException : {e.Message}"); } Console.WriteLine($"Press Enter to exit...."); Console.ReadLine(); Console.WriteLine("Hello, World!"); }

 

注意一定 服务器端 一定要启用 https 协议 如果是 http协议 会遇到各种莫名其妙的问题

http3 跟http2的配置一样 待验证 

我这里目前是win10系统好像不支持 http3.0 根据官方描述 目前至少需要win11 才支持 待验证

我目前本机配置了请求协议最高是只支持 http2.0的

 

 

 

 

posted @ 2023-02-02 16:46  刘小吉  阅读(112)  评论(0编辑  收藏  举报