如果我的 grpc 客户端是通过 AddGrpcClient 扩展创建的,我会收到此异常:
builder.Services.AddGrpcClient<MyClient>(options => options.Address = new Uri("https://localhost:50051"));
Grpc.Core.RpcException:'Status(StatusCode =“内部”,详细信息=“坏” gRPC 响应。响应协议降级为 HTTP/1.1。")'
但是,如果我的客户端是这样“手动”创建的:
using var channel = GrpcChannel.ForAddress("https://localhost:50051")
MyClient client = new(channel);
然后我就可以成功发出请求了。我在这里缺少什么?
AddGrpcClient
使用gRPC客户端工厂,它依赖于.NET的HttpClient提供的默认HTTP/2配置。MyClient client = new(channel);
使用自己的配置显式创建 GrpcChannel,这可能会绕过某些限制。您可以通过添加来确保 gRPC 服务器支持 http2
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenLocalhost(50051, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
});
});
配置httpclienthandler时尝试使用tls1.2
builder.Services.AddGrpcClient<MyClient>(options =>
{
options.Address = new Uri("https://localhost:50051");
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
SslProtocols = System.Security.Authentication.SslProtocols.Tls12
};
}
);