首页 > 解决方案 > 在 .net Core API 3.1 版中为 grpc 和 rest API 配置单独的端口

问题描述

之前我们使用.net core 2.1 API,在同一个项目中我们暴露了两个端口,一个用于rest API,另一个用于GRPC

下面是我们的启动和程序文件的样子

启动文件

  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //Proces for GRPC server binding
        Server server = new Server
        {
            Services = { HealthCheck.BindService(new HealthCheckController()),
                         },
            Ports = { new ServerPort("0.0.0.0", 5001, ServerCredentials.Insecure) }
        };
        //Start GRPC server
        server.Start();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }

程序文件

public static class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
    }
}

现在我们想将同一个项目迁移到 .net core 3.1,并且想维护两个单独的端口,一个用于 GRPC,另一个用于 REST API

下面是我们的启动和程序文件的样子

启动文件

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGrpcService<HealthCheckController>();
            endpoints.MapControllers();
        });
        //Start GRPC server

    }

程序文件

    public static class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }


    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

但问题是在迁移到 .net core 3.1 后,我们只能在同一个端口上使用这两种服务,任何关于我们如何为 GRPC 和 Rest API 分离端口的帮助都非常感谢。

标签: asp.netrestgrpcasp.net-core-3.1

解决方案


我不确定 .net 3.1 是否或为什么需要共享相同的端口(Can I combine a gRPC and webapi app into a .NET Core 3.0 in C#?似乎表明,至少对于 3.0,情况并非如此)。如果您确实需要共享端口,您可能需要考虑使用带有反向代理的 Kestrel ( https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel?view=aspnetcore- 3.1#when-to-use-kestrel-with-a-reverse-proxy),它应该能够根据其类型路由流量。


推荐阅读