【问题标题】:Publish two different endpoints on Kestrel for two different endpoints on ASP.NET Core在 Kestrel 上为 ASP.NET Core 上的两个不同端点发布两个不同的端点
【发布时间】:2019-12-07 23:25:04
【问题描述】:

我有一个 ASP.NET Core 应用程序,它有两个端点。一个是MVC,另一个是Grpc。我需要红隼在不同的套接字上发布每个端点。示例:localhost:8888 (MVC) 和 localhost:8889 (Grpc)。

我知道如何在 Kestrel 上发布两个端点。但问题是它在两个端点上发布 MVC 和 gRPC,我不希望这样。这是因为我需要 Grpc 请求使用 Http2。另一方面,我需要 MVC 请求使用 Http1

在我的 Statup.cs 上

public void Configure(IApplicationBuilder app)
{
    // ....
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGrpcService<ComunicacaoService>();
        endpoints.MapControllerRoute("default",
                                      "{controller}/{action=Index}/{id?}");
    });
    // ...

我需要一种方法让endpoints.MapGrpcService&lt;ComunicacaoService&gt;(); 在一个套接字上发布,endpoints.MapControllerRoute("default","{controller}/{action=Index}/{id?}"); 在另一个套接字上发布。

【问题讨论】:

    标签: c# asp.net-mvc grpc endpoint kestrel-http-server


    【解决方案1】:

    这是适合我的配置:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
               webBuilder.ConfigureKestrel(options =>
               {
                   options.Listen(IPAddress.Loopback, 55001, cfg =>
                   {
                       cfg.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http2;
                   });
    
                   options.Listen(IPAddress.Loopback, 55002, cfg =>
                   {
                       cfg.Protocols = Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols.Http1;
                   }); 
               });
    
               webBuilder.UseStartup<Startup>();
           });
    

    或者在 appsettings.json 中:

      "Kestrel": {
        "Endpoints": {
          "Grpc": {
            "Protocols" :  "Http2",
            "Url": "http://localhost:55001"
          },
          "webApi": {
            "Protocols":  "Http1",
            "Url": "http://localhost:55002"
          }
        }
      }
    

    【讨论】:

    • 感谢您的回答。我还有一个小问题。我不确定如何在启动文件上处理这个问题。如果我认为正确,您的代码将在两个套接字上发布这两种服务,因为这并没有明确说明在一个端口上发布一个服务而在另一个端口上发布另一个服务
    • 据我了解,两个中间件都将出现在两个端点上,只是 GRPC 仅适用于 HTTP2
    • 我明白了。这不完全是我正在寻找的东西,而是一个为我写答案的时间。谢谢大佬!
    • 您是否尝试过实例化、构建和运行两个 IHostBuilder(每个都单独配置,一个用于 gRPC,一个用于 MVC),然后为两者都使用 Task.WhenAll?
    • @Stonehead 实际上,没有。这似乎是一个非常棒的主意。我试试看,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多