gRPC-Web: Bringing gRPC to Browser Applications

gRPC is great for microservices, but browsers don’t support HTTP/2 trailers required for standard gRPC. **gRPC-Web** is the protocol adaptation that makes it possible. In .NET, we can now host gRPC-Web services natively alongside standard gRPC.

Configuring .NET Server

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddGrpc();
}

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();

    app.UseGrpcWeb(); // Enable Middleware

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGrpcService<GreeterService>()
            .EnableGrpcWeb(); // Enable on Endpoint
    });
}

Client Consumption

// Blazor WebAssembly Client
var handler = new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler());
var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions 
{ 
    HttpHandler = handler 
});

var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "User" });

Key Takeaways

  • No need for an external Envoy proxy anymore (though still valid).
  • Performance is better than JSON/REST due to Protobuf serialization.
  • Streaming is supported (Server Streaming only for now in browsers).

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.