问题描述
我如何(并且有可能)在C#Kestrel Web服务器中通过纯HTTP启用HTTP2?所有Microsoft文档均指示必须使用https/TLS,但我拥有将在负载均衡器或nginx之后运行的服务,因此不需要第二层https.官方的http2规范指示不需要https.
How do I (and is it possible) to enable http2 over plain http in the C# Kestrel web server? All Microsoft documentation indicates that https/TLS is required, but I have services that will be running behind a load-balancer or nginx and as such don't need a second layer of https. The official http2 spec indicates that https is not required.
推荐答案
使用未加密的http2的方案是负载平衡器,代理等.
Scenarios to use unencrypted http2 are load balancers, proxies, etc.
要通过未加密的频道使用http2,您必须做三件事.
You must do three things to use http2 over unencrypted channel.
设置Kestrel以在服务器上使用http2:
builder.ConfigureWebHostDefaults((webBuilder) =>
{
// this will keep your other end points settings such as --urls parameter
webBuilder.ConfigureKestrel((options) =>
{
// trying to use Http1AndHttp2 causes http2 connections to fail with invalid protocol error
// according to Microsoft dual http version mode not supported in unencrypted scenario: https://docs.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-3.0
options.ConfigureEndpointDefaults(lo => lo.Protocols = HttpProtocols.Http2);
});
});
对于.net 5+,创建您的 HttpClient
实例,然后创建一条消息并指定版本:
For .net 5+, create your HttpClient
instance, then create a message and specify the version:
var request = new HttpRequestMessage(HttpMethod.Get, uri)
{
Version = HttpVersion.Version20,
VersionPolicy = HttpVersionPolicy.RequestVersionOrHigher
};
对于.net core 3.1和更低版本,请设置一个标志以启用未加密的http2.然后,在创建 HttpClient
时,指定版本:
For .net core 3.1 and older, set a flag to enable http2 unencrypted. Then, when you create an HttpClient
, specify the version:
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
var client = new HttpClient { BaseAddress = new Uri(baseUrl), DefaultRequestVersion = new Version(2, 0) };
如果需要在完全未加密的主机上同时支持http1和http2,则需要监听两个端口,每个http版本一个.然后,您的负载平衡器或代理将需要处理http版本并直接指向相应的端口.
If you need to support both http1 and http2 on a completely unencrypted host, then you will need to listen on two ports, one for each http version. Then your load balancer or proxy would need to handle the http version and direct to the appropriate port.
您不会在浏览器上看到http2,并且可能会遇到协议错误,因此在这种情况下,您可以将http1协议指令仅用于开发环境.这并不理想,但至少可以让您在本地进行测试.
You won't see http2 on your browser and will likely get a protocol error, so in those cases you can use an http1 protocol directive just for development environment. Not ideal, but it at least lets you test locally.
这篇关于如何通过纯HTTP在C#Kestrel Web服务器中启用http2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!