Search code examples
c#.netasp.net-core.net-coregrpc

Bind gRPC services to specific port in aspnetcore


Using aspnetcore 3.1 and the Grpc.AspNetCore nuget package, I have managed to get gRPC services running successfully alongside standard asp.net controllers as described in this tutorial.

However I would like to bind the gRPC services to a specific port (e.g. 5001), preferably through configuration instead of code if possible. This is because I would like to limit how my gRPC services are exposed.

The closest I have come has been using RequireHost when mapping the endpoints:

// Startup.cs
public void Configure(IApplicationBuilder app)
{
    // ...
    
    app.useEndpoints(endpoints => 
    {
        endpoints.MapGrpcService<MyService>()
            .RequireHost("0.0.0.0:5001");
    }); 
}

This seems to do what I want but I can't find any documentation about it, and it requires configuration in code per service. Perhaps there is a better way?


Solution

  • As far as I know, there is no other way to set a specific port for the GRPC service.

    The grpc service is also running on the asp.net core kestrel server, the server will listen the port not the service.

    If your asp.net core application just has GRPC service, you could just set the kestrel server's listen port to 5001.

    If you have multiple service like MVC web api or else, RequireHost is the best workaround to allow only specific port access the grpc service.

    If you want to prompt the routing system for GRPC service to require the specified port, you could use below port:

     routes.MapGrpcService<MyService>().RequireHost("*:5001");