使用 aspnetcore 3.1
和 Grpc.AspNetCore
nuget 包,我已经设法使 gRPC 服务与标准 asp.net Controller 一起成功运行,如 this tutorial 中所述.
但是,我想将 gRPC 服务绑定(bind)到特定端口(例如 5001),如果可能的话,最好通过配置而不是代码。这是因为我想限制我的 gRPC 服务的公开方式。
我最接近的一直是使用 RequireHost
映射端点时:
// Startup.cs
public void Configure(IApplicationBuilder app)
{
// ...
app.useEndpoints(endpoints =>
{
endpoints.MapGrpcService<MyService>()
.RequireHost("0.0.0.0:5001");
});
}
这似乎符合我的要求,但我找不到任何关于它的文档,并且它需要在每个服务的代码中进行配置。也许有更好的方法?
最佳答案
这适用于 Kestrel(服务器端):
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Loopback, 5000);
options.Listen(IPAddress.Loopback, 5005, configure => configure.UseHttps());
});
webBuilder.UseStartup<Startup>();
});
客户端: var httpHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
using var channel = GrpcChannel.ForAddress("https://localhost:5005", new GrpcChannelOptions { HttpHandler = httpHandler } );
var client = new Greeter.GreeterClient(channel);
笔记: var httpHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback =
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
当您拥有没有信任链的自签名证书时(主要是在开发时)。AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
是为了支持http。
关于c# - 将 gRPC 服务绑定(bind)到 aspnetcore 中的特定端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63827667/