Add a .proto file to a C# app
<ItemGroup> <Protobuf Include="Protos\greet.proto" GrpcServices="Server" /> </ItemGroup>
C# Tooling support for .proto files
Server:
<PackageReference Include="Grpc.AspNetCore" Version="2.28.0" />
Client:
<PackageReference Include="Google.Protobuf" Version="3.11.4" /> <PackageReference Include="Grpc.Net.Client" Version="2.28.0" /> <PackageReference Include="Grpc.Tools" Version="2.28.1">
Generated C# assets
Server Side:
To ensure only the server assets are generated in a server project, the GrpcServices attribute is set to Server.
<ItemGroup> <Protobuf Include="Protos\greet.proto" GrpcServices="Server" /> </ItemGroup>
public class GreeterService : Greeter.GreeterBase { private readonly ILogger<GreeterService> _logger; public GreeterService(ILogger<GreeterService> logger) { _logger = logger; } public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context) { return Task.FromResult(new HelloReply { Message = "Hello " + request.Name }); } }
Client Side:
static async Task Main(string[] args) { // The port number(5001) must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync( new HelloRequest { Name = "GreeterClient" }); Console.WriteLine("Greeting: " + reply.Message); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
References
https://docs.microsoft.com/en-us/aspnet/core/grpc/basics?view=aspnetcore-5.0