create grpc server in csharp

To create a gRPC server in C#, follow these steps:

  1. Create a new project in Visual Studio using the .NET Core template.
  2. In the project properties, set the Target Framework to .NET Core and the Output Type to Console Application.
  3. Add the following NuGet packages to your project: Grpc.AspNetCore, Google.Protobuf, and Google.Api.CommonProtos.
  4. Create a new class that implements your gRPC service. For example:
main.cs
public class MyGreeterService : Greeter.GreeterBase
{
    public override async Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
    {
        return new HelloReply
        {
            Message = "Hello " + request.Name
        };
    }
}
266 chars
11 lines
  1. In your Main method, create a new instance of the server and add your gRPC service.
main.cs
static void Main(string[] args)
{
    var host = "localhost";
    var port = 50051;
    var server = new Server
    {
        Services = { Greeter.BindService(new MyGreeterService()) },
        Ports = { new ServerPort(host, port, ServerCredentials.Insecure) }
    };
    server.Start();
    Console.WriteLine($"Server listening on {host}:{port}");
    Console.ReadKey();
}
374 chars
14 lines
  1. Start your gRPC server and you're done!

Note: Don't forget to update the Greeter namespace to match your proto file.

gistlibby LogSnag