Microservice Architecture

Use gRPC in the browser with gRPC-Web and .NET5

Build High-Performance Services using gRPC and .NET 5

© All rights reserved

1 — The Problem

© HTTP 1.1 and HTTP/2 High-Level Structure

2 — The Solution

Source: https://grpc.io/

3 — Getting Started with gRPC-Web for .NET

Set build action to Protobuf compiler
using StockServices.Protos;public class StockService  : Stock.StockBase{
private static List<Product> _allProducts = new List<Product>();
public override Task<Result> AddProduct(Product request, ServerCallContext context){}
if (string.IsNullOrEmpty(request.Name))return Task.FromResult<Result>(new Result { Msg = "Product Name Can't be nulled", Status = false });if (_allProducts.FirstOrDefault(f => f.Code == request.Code) != null)return Task.FromResult<Result>(new Result { Msg = "Product is already Added", Status = false });_allProducts.Add(request);return Task.FromResult<Result>(new Result { Msg = "Added. Total Products: "+_allProducts.Count.ToString(), Status = true });}
public override async Task GetAllProducts(Empty request, IServerStreamWriter<Product> responseStream, ServerCallContext context){foreach (var each in _allProducts){
await responseStream.WriteAsync(each);
app.UseGrpcWeb();app.UseEndpoints(endpoints =>{endpoints.MapGrpcService<StockService>().EnableGrpcWeb();});
gRPC- Web — Javascript client
gRPC- Web — Javascript client
protoc greet.proto --js_out=import_style=commonjs:CHANGE_TO_SCRIPTS_DIRECTORY --grpc-web_out=import_style=commonjs,mode=grpcwebtext:CHANGE_TO_SCRIPTS_DIRECTORY --plugin=protoc-gen-grpc-web=CHANGE_TO_PROTOC_GEN_GRPC_WEB_EXE_PATH
var client = new StockClient(window.location.origin);
var request = new Product(); 
client.addProduct(request, {}, (err, response) => { resultText.innerHTML = htmlEscape(response.getMsg()); 

Server Streaming

grpc app — invokes a server streaming call (GetAllProducts)
grpc app — invokes a server streaming call (GetAllProducts)

var request = new Empty();
streamingCall = client.getAllProducts(request, {});
streamingCall.on(‘data’, function (response)
trProducts.innerHTML += “<tr><td>” + htmlEscape(response.getName()) + “</td><td>” + htmlEscape(response.getCode())+”</td></tr>”; });
streamingCall.on('end', function () { 
console.log("Stream ended");


Solution Architect — Developing enterprise-grade applications for more than a decade | AI and IoT Enthusiast.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store