我如何(并且有可能)在C#Kestrel Web服务器上通过纯HTTP启用HTTP2?所有Microsoft文档均指示必须使用https / TLS,但我拥有将在负载均衡器或nginx之后运行的服务,因此不需要第二层https。官方的http2规范指示不需要https。
使用未加密的http2的方案是负载平衡器,代理等。
您必须做三件事才能在未加密的通道上使用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);
});
});
HttpClient
实例,然后创建一条消息并指定版本:var request = new HttpRequestMessage(HttpMethod.Get, uri)
{
uri,
Version = HttpVersion.Version20,
VersionPolicy = HttpVersionPolicy.RequestVersionOrHigher
};
HttpClient
,请指定版本: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版本并直接指向相应的端口。
您不会在浏览器上看到http2,并且可能会收到协议错误,因此在这种情况下,您可以将http1协议指令仅用于开发环境。不理想,但是至少可以让您在本地进行测试。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句