Skip to content

albinronnkvist/GrpcCodeFirst

Repository files navigation

Code-first gRPC in .NET

Code-first gRPC using .NET types to define service and message contracts. It is made possible using the protobuf-net.Grpc package.

Validation

Request message validation is done with the grpc-aspnetcore-validator package. It is integrated with Fluent Validation.

To list validation errors on the client, see the following example:

try
{
    using var channel = GrpcChannel.ForAddress("https://localhost:7039");
    var client =  channel.CreateGrpcService<IBouncerService>();
    
    // Empty Name value and incorrect Age value that raises validation errors
    var reply = await client.EnterClubAsync(new EnterRequest { Name = "", Age = -25 });
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.InvalidArgument)
{
    var errors = ex.GetValidationErrors(); // Gets list of validation errors
}

Authentication / Authorization

Azure AD Client Credentials Flow is used.

See the Azure AD Client Credentials Flow with ASP.NET Core Web API article for a full tutorial on how to implement it.

Testing

It is possible to test the gRPC service using Postman or gRPCurl.

You can also run tests from the IntegrationTest project. Read more about testing gRPC services in ASP.NET Core.

The reflection service is also enabled, which allows clients to dynamically discover the available methods and their input and output types.

Docker

A built-in containers approach is used:

  • Build image with dotnet publish: dotnet publish --os linux --arch x64 -c Release
  • Run container: docker run -p 5000:80 -d [image-name]:[tag]
  • Push to remote repository:
    • First change tag: docker tag [image-name]:[tag] [remote-repository-url]/[image-name]:[new-tag]
    • Then push: docker push [remote-repository-url]/[image-name]:[new-tag]

Jammy-chiseled is used as the base image. It's a small and secure image with only the packages required to run the container, no package manager, no shell and non-root user.

Releases

No releases published

Packages

No packages published

Languages