天天看點

在 ASP.NET Core 中建立 gRPC 用戶端和伺服器

作者:靜觀其變Lee

本教程示範了如何建立 .NET Core gRPC 用戶端和 ASP.NET Core gRPC 伺服器。 最後會生成與 gRPC Greeter 服務進行通信的 gRPC 用戶端。

在本教程中,你将了解:

  • 建立 gRPC 伺服器。
  • 建立 gRPC 用戶端。
  • 使用 gRPC Greeter 服務測試 gRPC 用戶端。

先決條件

  • Visual Studio
  • Visual Studio Code
  • Visual Studio for Mac

帶有 ASP.NET 和 Web 開發工作負載的 Visual Studio 2022。

建立 gRPC 服務

  • Visual Studio
  • Visual Studio Code
  • Visual Studio for Mac

啟動 Visual Studio 2022 并選擇“建立新項目”。在“建立新項目”對話框中,搜尋 gRPC。 選擇“ASP.NET Core gRPC 服務”,并選擇“下一步” 。在“配置新項目”對話框中,為“項目名稱”輸入 GrpcGreeter。 将項目命名為“GrpcGreeter”非常重要,這樣在複制和粘貼代碼時命名空間就會比對。選擇“下一頁”。在“其他資訊”對話框中,選擇“.NET 6.0 (長期支援)”,然後選擇“建立”。

運作服務

  • Visual Studio
  • Visual Studio Code
  • Visual Studio for Mac
  • 按 Ctrl+F5 以在不使用調試程式的情況下運作。如果尚未将項目配置為使用 SSL,Visual Studio 顯示以下對話:
  • 如果信任 IIS Express SSL 證書,請選擇“是”。将顯示以下對話框:
  • 如果你同意信任開發證書,請選擇“是”。有關信任 Firefox 浏覽器的資訊,請參閱 Firefox SEC_ERROR_INADEQUATE_KEY_USAGE 證書錯誤。Visual Studio:啟動 Kestrel 伺服器。啟動浏覽器。導航到 http://localhost:port,如 http://localhost:7042。端口:随機配置設定給應用的端口号。localhost:本地計算機的标準主機名。 Localhost 僅為來自本地計算機的 Web 請求提供服務。

日志顯示在 https://localhost:<port> 上偵聽的服務,其中 <port> 是在 Properties/launchSettings.json 中建立和設定項目時随機配置設定的 localhost 端口号。

控制台複制

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:<port>
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
           

備注

gRPC 模闆配置為使用傳輸層安全性 (TLS)。 gRPC 用戶端需要使用 HTTPS 調用伺服器。 在 gRPC 服務項目的 Properties\launchSettings.json 檔案中建立和設定項目時,将随機配置設定 gRPC 服務 localhost 端口号。

macOS 不支援 ASP.NET Core gRPC 及 TLS。 在 macOS 上成功運作 gRPC 服務需要其他配置。 有關詳細資訊,請參閱無法在 macOS 上啟用 ASP.NET Core gRPC 應用。

檢查項目檔案

GrpcGreeter 項目檔案:

  • Protos/greet.proto:定義 Greeter gRPC,并用于生成 gRPC 伺服器資産。 有關詳細資訊,請參閱 gRPC 介紹。
  • Services 檔案夾:包含 Greeter 服務的實作。
  • appSettings.json:包含配置資料,如 Kestrel 使用的協定。 有關詳細資訊,請參閱 ASP.NET Core 中的配置。
  • Program.cs,其中包含:gRPC 服務的入口點。 有關詳細資訊,請參閱 ASP.NET Core 中的 .NET 通用主機。配置應用行為的代碼。 有關詳細資訊,請參閱應用啟動。

在 .NET 控制台應用中建立 gRPC 用戶端

  • Visual Studio
  • Visual Studio Code
  • Visual Studio for Mac

打開 Visual Studio 的第二個執行個體并選擇“建立新項目”。在“建立新項目”對話框中,選擇“控制台應用程式”,然後選擇“下一步” 。在“項目名稱”文本框中,輸入“GrpcGreeterClient”,然後選擇“下一步” 。在“其他資訊”對話框中,選擇“.NET 6.0 (長期支援)”,然後選擇“建立”。

添加所需的 NuGet 包

gRPC 用戶端項目需要以下 NuGet 包:

  • Grpc.Net.Client,其中包含 .NET Core 用戶端。
  • Google.Protobuf 包含适用于 C# 的 Protobuf 消息。
  • Grpc.Tools,其中包含适用于 Protobuf 檔案的 C# 工具支援。 運作時不需要工具包,是以依賴項标記為 PrivateAssets="All"。
  • Visual Studio
  • Visual Studio Code
  • Visual Studio for Mac

通過包管理器控制台 (PMC) 或管理 NuGet 包來安裝包。

用于安裝包的 PMC 選項

  • 從 Visual Studio 中,依次選擇“工具”>“NuGet 包管理器”>“包管理器控制台”
  • 從“包管理器控制台”視窗中,運作 cd GrpcGreeterClient 以将目錄更改為包含 GrpcGreeterClient.csproj 檔案的檔案夾。
  • 運作以下指令:
  • PowerShell複制
  • Install-Package Grpc.Net.Client Install-Package Google.Protobuf Install-Package Grpc.Tools

管理 NuGet 包選項以安裝包

  • 右鍵單擊“解決方案資料總管”>“管理 NuGet 包”中的項目 。
  • 選擇“浏覽”頁籤。
  • 在搜尋框中輸入 Grpc.Net.Client。
  • 從“浏覽”頁籤中選擇“Grpc.Net.Client”包,然後選擇“安裝” 。
  • 為 Google.Protobuf 和 Grpc.Tools 重複這些步驟。

添加 greet.proto

  • 在 gRPC 用戶端項目中建立 Protos 檔案夾。
  • 從 gRPC Greeter 服務将 Protos\greet.proto 檔案複制到 gRPC 用戶端項目中的 Protos 檔案夾 。
  • 将 greet.proto 檔案中的命名空間更新為項目的命名空間:
  • 複制
  • option csharp_namespace = "GrpcGreeterClient";
  • 編輯 GrpcGreeterClient.csproj 項目檔案:
  • Visual Studio
  • Visual Studio Code
  • Visual Studio for Mac

右鍵單擊項目,并選擇“編輯項目檔案”。

  • 添加具有引用 greet.proto 檔案的 <Protobuf> 元素的項組:
  • XML複制
  • <ItemGroup> <Protobuf Include="Protos\greet.proto" GrpcServices="Client" /> </ItemGroup>

建立 Greeter 用戶端

  • 建構用戶端項目,以在 GrpcGreeterClient 命名空間中建立類型。

備注

GrpcGreeterClient 類型是由生成程序自動生成的。 工具包 Grpc.Tools 基于 greet.proto 檔案生成以下檔案:

  • GrpcGreeterClient\obj\Debug\[TARGET_FRAMEWORK]\Protos\Greet.cs:用于填充、序列化和檢索請求和響應消息類型的協定緩沖區代碼。
  • GrpcGreeterClient\obj\Debug\[TARGET_FRAMEWORK]\Protos\GreetGrpc.cs:包含生成的用戶端類。

有關 Grpc.Tools 自動生成的 C# 資産的詳細資訊,請參閱使用 C# 的 gRPC 服務:生成的 C# 資産。

  • 使用以下代碼更新 gRPC 用戶端 Program.cs 檔案。
  • C#複制
  • using System.Threading.Tasks; using Grpc.Net.Client; using GrpcGreeterClient; // The port number must match the port of the gRPC server. using var channel = GrpcChannel.ForAddress("https://localhost:7042"); 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();
  • 在前面突出顯示的代碼中,将 localhost 端口号 7042 替換為在 GrpcGreeter 服務項目的 Properties/launchSettings.json 中指定的 HTTPS 端口号。

Program.cs 包含 gRPC 用戶端的入口點和邏輯。

通過以下方式建立 Greeter 用戶端:

  • 執行個體化 GrpcChannel,使其包含用于建立到 gRPC 服務的連接配接的資訊。
  • 使用 GrpcChannel 構造 Greeter 用戶端:

C#複制

// The port number must match the port of the gRPC server.
using var channel = GrpcChannel.ForAddress("https://localhost:7042");
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();
           

Greeter 用戶端會調用異步 SayHello 方法。 随即顯示 SayHello 調用的結果:

C#複制

// The port number must match the port of the gRPC server.
using var channel = GrpcChannel.ForAddress("https://localhost:7042");
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();
           

使用 gRPC Greeter 服務測試 gRPC 用戶端

  • Visual Studio
  • Visual Studio Code
  • Visual Studio for Mac

在 Greeter 服務中,按 Ctrl+F5 在不使用調試程式的情況下啟動伺服器。在 GrpcGreeterClient 項目中,按 Ctrl+F5 在不使用調試程式的情況下啟動用戶端。

用戶端向該服務發送一條包含具有其名稱“GreeterClient”的消息的問候資訊。 該服務會發送“Hello GreeterClient”消息作為答複。 “Hello GreeterClient”答複将在指令提示符中顯示:

控制台複制

Greeting: Hello GreeterClient
Press any key to exit...
           

gRPC 服務在寫入指令提示符的日志中記錄成功調用的詳細資訊:

控制台複制

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:<port>
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\GH\aspnet\docs\4\Docs\aspnetcore\tutorials\grpc\grpc-start\sample\GrpcGreeter
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/2 POST https://localhost:<port>/Greet.Greeter/SayHello application/grpc
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint 'gRPC - /Greet.Greeter/SayHello'
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
      Executed endpoint 'gRPC - /Greet.Greeter/SayHello'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished in 78.32260000000001ms 200 application/grpc
           

通過添加以下行來更新 appsettings.Development.json 檔案:

複制

"Microsoft.AspNetCore.Hosting": "Information",
"Microsoft.AspNetCore.Routing.EndpointMiddleware": "Information"
           

備注

本文中的代碼需要 ASP.NET Core HTTPS 開發證書來保護 gRPC 服務。 如果 .NET gRPC 用戶端失敗并顯示消息 The remote certificate is invalid according to the validation procedure. 或 The SSL connection could not be established.,則開發證書不受信任。 要解決此問題,請參閱使用不受信任/無效的證書調用 gRPC 服務。