创建gRPC服务器应用时遭遇Grpc.Core.RpcException错误求助
错误信息
Grpc.Core.RpcException: 'Status(StatusCode="Unavailable", Detail="启动gRPC调用时出错。HttpRequestException: 发送请求时发生错误。IOException: 请求已中止。Http2ConnectionException: HTTP/2服务器在连接上发送了无效数据。HTTP/2错误码 'PROTOCOL_ERROR' (0x1)。", DebugException="System.Net.Http.HttpRequestException: 发送请求时发生错误。")'
问题分析
这个错误核心是HTTP/2协议不兼容,常见触发原因包括:
- 客户端与服务器的HTTP协议版本不匹配(如客户端用HTTP/1.1连接仅支持HTTP/2的服务器)
- 地址协议(HTTP/HTTPS)不匹配
- gRPC服务注册或调用的配置有误
- 命名空间不匹配导致服务路由失败
解决方案
1. 修正客户端连接配置
若你的gRPC服务器使用HTTPS(ASP.NET Core默认配置),客户端地址需改为https://localhost:5001(默认HTTPS端口),而非http://localhost:5000。同时移除不必要的证书验证代码(仅当服务器证书不可信时保留):
修改后的客户端Program.cs:
using Grpc.Net.Client; namespace GrpcClient { class Program { static async Task Main(String[] args) { var channel = GrpcChannel.ForAddress("https://localhost:5001"); // 注意使用proto生成的命名空间下的客户端类 var client = new GrpcConsoleServer.Customer.CustomerClient(channel); var customerRequested = new GrpcConsoleServer.CustomerRequest { Id = 1 }; var response = await client.CustomerInfoAsync(customerRequested); Console.WriteLine($"Name: {response.Firstname}\nLastName: {response.Lastname}\nAge: {response.Age}"); Console.ReadLine(); } } }
2. 确保服务器正确注册gRPC服务
服务器端需在Program.cs中完成gRPC服务的注册与映射:
var builder = WebApplication.CreateBuilder(args); // 添加gRPC服务支持 builder.Services.AddGrpc(); var app = builder.Build(); // 映射自定义的CustomerService1 app.MapGrpcService<GrpcConsoleServer.Service.CustomerService1>(); app.Run();
3. 验证命名空间一致性
你的.proto文件指定了csharp_namespace = "GrpcConsoleServer",因此生成的所有gRPC类都属于该命名空间。客户端调用时必须使用完整命名空间(如GrpcConsoleServer.Customer.CustomerClient),避免因命名空间错误导致服务路由失败。
4. 确保服务器启用HTTP/2
ASP.NET Core服务器默认已启用HTTP/2。若使用HTTP而非HTTPS,需在appsettings.json中显式配置:
{ "Kestrel": { "EndpointDefaults": { "Protocols": "Http2" } } }
内容的提问来源于stack exchange,提问作者Dee

