iT邦幫忙

2025 iThome 鐵人賽

DAY 20
1
Software Development

30 天的 .Net gRPC 迷途系列 第 20

Day20 gRPC-Web 的使用

  • 分享至 

  • xImage
  •  

在 .NET 的 Program.cs 中設定後,瀏覽器即可呼叫 gRPC Server —— 但僅支援「一元」與「Server Stream」兩種方式

這是因為瀏覽器尚未原生支援 HTTP/2 的完整 gRPC(如雙向串流),未來瀏覽器若支援完整 gRPC,限制有望解除

// ...
// 針對全部服務設定,不需要個別設定
app.UseGrpcWeb(new GrpcWebOptions { DefaultEnabled = true });
app.MapGrpcService<GreeterService>();

// or

app.UseGrpcWeb();
// 針對特定的服務啟用
app.MapGrpcService<GreeterService>().EnableGrpcWeb();

啟用後,跨伺服器呼叫的話,需要啟用 CORS,並且若使用 Kestrel 當服務也要做下面的設定

{
  "Kestrel": {
    "EndpointDefaults": {
      // 要改成支援 Http1、Http2
      "Protocols": "Http1AndHttp2"
    }
  }
}

裡面還有很多像 javascript(需搭配 NPM) 、.Net Client 端的一些設定,可以參考微軟的官方說明

參考:
https://learn.microsoft.com/zh-tw/aspnet/core/grpc/grpcweb?view=aspnetcore-9.0


上一篇
Day19 gRPC 進階屬性格式(跨專案)
系列文
30 天的 .Net gRPC 迷途20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言