Как указать режим HTTP / 2 «предварительные знания» для HttpClient в ядре do tnet? - PullRequest
1 голос
/ 05 марта 2020

Используя do tnet Core 3.1, следующий сервер принимает запросы HTTP / 2:

using System;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using System.Threading;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core;

namespace http2
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .ConfigureKestrel((context, serverOptions) =>
                {
                    serverOptions.ListenLocalhost(8080, listenOptions =>
                    {
                        listenOptions.Protocols = HttpProtocols.Http2; // this line is important
                    });
                });
    }

    class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.Run(context => ProcessAsync(context));
        }

        internal async Task<bool> ProcessAsync(HttpContext context)
        {
            await context.Response.WriteAsync("This is the response: toto");
            return true;
        }
    }
}

Например, вы получите ответ, если попытаетесь: curl --silent --http2-prior-knowledge http://localhost:8080

My вопрос в том, как на самом деле делать то, что делает curl? Но в C#.

я пробовал:

static void ClientCode(object parameter)
{
      SocketsHttpHandler handler = new SocketsHttpHandler();
      using (var client = new HttpClient(handler))
      {
           var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8080");
           request.Version = new Version(2, 0);

           var response = client.SendAsync(request).Result;
           if (response.IsSuccessStatusCode)
           {
                var s = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine(s);
           }
      }
}

Но я просто получаю исключение.

Можно ли использовать режим предшествующего знания с HttpClient в C# и tnet Core?

1 Ответ

2 голосов
/ 06 марта 2020

Мой вопрос о том, как на самом деле делать то, что делает curl? Но в C#.

Пожалуйста, попробуйте установить переключатель System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport в положение true, как показано ниже.

AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

SocketsHttpHandler handler = new SocketsHttpHandler();
using (var client = new HttpClient(handler))
{
    var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8080");
    request.Version = new Version(2, 0);

    var response = client.SendAsync(request).Result;

    if (response.IsSuccessStatusCode)
    {
        var s = response.Content.ReadAsStringAsync().Result;
        Console.WriteLine(s);
    }
}

Результат теста

enter image description here

...