How to enable HTTP2 in Kestrel

Viewed 691

IIS is not involved. Everything is running on local computer, Windows 10 x64. Tried creating different kinds of projects, like Blazor and Web API, the result is on the screenshot - invalid response, although in IE 11 it shows some weird characters. Chrome and MS Edge don't even try to display the page.

In the code below I tried different combinations of protocols, on the same port and IP or different ones. Only endpoints using HTTP1 work fine. Suggestions here didn't help.

How do I enable HTTP2 in Kestrel?

public static IWebHostBuilder CreateHostBuilder(string[] args)
{
  var configuration = new ConfigurationBuilder()
    .AddCommandLine(args)
    .Build();

  var environment = WebHost
    .CreateDefaultBuilder(args)
    .UseConfiguration(configuration)
    .UseIISIntegration()
    .UseContentRoot(Directory.GetCurrentDirectory())
    //.UseUrls("http://localhost:5000", "https://localhost:5001")
    .UseStaticWebAssets()
    .UseStartup<Startup>()
    .ConfigureKestrel(options =>
    {
      //options.ConfigureEndpointDefaults(o => o.Protocols = HttpProtocols.Http2);
      options.Listen(IPAddress.Loopback, 0, o =>
      {
        //o.UseHttps("Certificate.pfx", "Demo");
        o.Protocols = HttpProtocols.Http2;
      });

      options.Listen(IPAddress.Loopback, 0, o =>
      {
        o.UseHttps("Certificate.pfx", "Demo");
        o.Protocols = HttpProtocols.Http1;
      });
    });

  return environment;
}

IE 11 vs MS Edge

1 Answers

https is required for http2
This works fine for net5.0 (checked in Chrome with protocol column enabled)

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.ConfigureKestrel(options =>
            {
                options.Listen(IPAddress.Any, 5000, o =>
                {
                    o.Protocols = HttpProtocols.Http2; // with this line or not - both works fine
                    o.UseHttps();
                });
            });
            webBuilder.UseStartup<Startup>();
        });

As per the docs

Starting with .NET Core 3.0, HTTP/2 is enabled by default

Use HTTP/2 with the ASP.NET Core Kestrel web server

Related