c# - 将 gRPC 服务绑定(bind)到 aspnetcore 中的特定端口

标签 c# .net asp.net-core .net-core grpc

使用 aspnetcore 3.1Grpc.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/

相关文章:

c# - 如何使用 EF 4.1 Code First 在运行时配置数据库连接

c# - 从列表中选择在成员函数上返回 true 的所有对象作为列表?

c# - 在 C# GUI 应用程序中将远程 Mysql 数据库同步到本地

c# - 在构造函数中自动调用父类(super class)方法

c# - 选择所有带有所有标签的帖子

c# - 在 ContextMenu 打开操作 wp7 上设置所选项目

c++ - 将敏感数据存储在 C++ 编译的二进制文件中是否安全?

c# - 如何在 C# .NET Core 中测试查询的执行时间

.net - swagger .net core API 操作错误的不明确 HTTP 方法

c# - ASP.NET 核心 : Error when using a custom DbContext while also using Identity