在 ASP.NET Core 上为两个不同的端点在 Kestrel 上发布两个不同的端点

Publish two different endpoints on Kestrel for two different endpoints on ASP.NET Core

我有一个 ASP.NET 核心应用程序,它有两个端点。一个是 MVC,另一个是 Grpc。我需要 kestrel 在不同的套接字上发布每个端点。示例: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<ComunicacaoService>(); 在一个套接字上发布,而 endpoints.MapControllerRoute("default","{controller}/{action=Index}/{id?}"); 在另一个套接字上发布。

这是适合我的配置:

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"
      }
    }
  }