Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a ASP.NET Core application that has two endpoints. One is the MVC and the other is the Grpc. I need that the kestrel publishs each endpoint on different sockets. Example: localhost:8888 (MVC) and localhost:8889 (Grpc).

I know how to publish two endpoints on Kestrel. But the problem is that it's publishing the MVC and the gRPC on both endpoints and I don't want that. This is because I need the Grpc requests use Http2. On the other hand, I need that MVC requests use Http1

on my Statup.cs I have

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

I need a way to make endpoints.MapGrpcService<ComunicacaoService>(); be published on one socket and the endpoints.MapControllerRoute("default","{controller}/{action=Index}/{id?}"); on another one.

like image 515
Douglas Ramos Avatar asked Jul 30 '19 14:07

Douglas Ramos


1 Answers

Here is the configuration that works for me:

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>();
       });

Alternatively in appsettings.json:

  "Kestrel": {
    "Endpoints": {
      "Grpc": {
        "Protocols" :  "Http2",
        "Url": "http://localhost:55001"
      },
      "webApi": {
        "Protocols":  "Http1",
        "Url": "http://localhost:55002"
      }
    }
  }
like image 171
ghord Avatar answered Sep 21 '22 08:09

ghord