You maybe think this is a bad title for this blog post? HTTP/2 support was already available for .NET Core 3.0. So why a blog post with the release of .NET Core 3.0?
The reason is that although it was possible to host an ASP.NET Core 2.0 application behind an HTTP/2 endpoint, the HttpClient class didnāt had support for it!
There are 2 ways that can be used to enable HTTP/2:
Enable HTTP/2 at the instance level
To enable HTTP/2 support at the instance level, you can set the DefaultRequestVersion when creating the HttpClient instance:
For example, the following code creates an HttpClient instance using HTTP/2 as its default protocol:
var client = new HttpClient() | |
{ | |
BaseAddress = new Uri("https://localhost:5001"), | |
DefaultRequestVersion = new Version(2, 0) | |
}; |
Of course even better is to use the HttpClientFactory to create and configure the HttpClient:
services.AddHttpClient<ICatalogService, CatalogService>(client => | |
{ | |
client.BaseAddress = new Uri("https://localhost:5001"), | |
client.DefaultRequestVersion = new Version(2, 0) | |
}) |
Enable HTTP/2 at the request level
It is also possible to create a single request using the HTTP/2 protocol:
var client = new HttpClient() { BaseAddress = new Uri("https://localhost:5001") }; | |
using (var request = new HttpRequestMessage(HttpMethod.Get, "/") { Version = new Version(2, 0) }) | |
using (var response = await client.SendAsync(request)) | |
Console.WriteLine(response.Content); |
Remark: Remember that HTTP/2 needs to be supported by both the server and the client. If either party doesn't support HTTP/2, both will use HTTP/1.1.