教學課程:在 ASP.NET Core 中建立 gRPC 用戶端和伺服器Tutorial: Create a gRPC client and server in ASP.NET Core

作者:John LuoBy John Luo

本教學課程示範如何建立 .NET Core gRPC 用戶端,以及 ASP.NET Core gRPC 伺服器。This tutorial shows how to create a .NET Core gRPC client and an ASP.NET Core gRPC Server.

在結束時,您將擁有可與 gRPC Greeter 服務通訊的 gRPC 用戶端。At the end, you'll have a gRPC client that communicates with the gRPC Greeter service.

檢視或下載範例程式碼 (如何下載)。View or download sample code (how to download).

在本教學課程中,您:In this tutorial, you:

  • 建立 gRPC 伺服器。Create a gRPC Server.
  • 建立 gRPC 用戶端。Create a gRPC client.
  • 利用 gRPC Greeter 服務來測試 gRPC 用戶端。Test the gRPC client service with the gRPC Greeter service.

PrerequisitesPrerequisites

建立 gRPC 服務Create a gRPC service

  • 啟動 Visual Studio,然後選取 [建立新專案]。Start Visual Studio and select Create a new project. 或者,從 Visual Studio 的 [檔案]**** 功能表中,選取 [新增]**** > [專案]****。Alternatively, from the Visual Studio File menu, select New > Project.

  • 在 [ 建立新專案 ] 對話方塊中,選取 [ gRPC 服務 ],然後選取 [下一步]In the Create a new project dialog, select gRPC Service and select Next:

    [建立新專案] 對話方塊

  • 將專案命名為 GrpcGreeterName the project GrpcGreeter. 請務必將專案命名為 GrpcGreeter,如此當您複製並貼上程式碼時,命名空間才會相符。It's important to name the project GrpcGreeter so the namespaces will match when you copy and paste code.

  • 選取 [建立]。Select Create.

  • 在 [建立新的 gRPC 服務]**** 對話方塊中:In the Create a new gRPC service dialog:

    • 已選取 [gRPC 服務]**** 範本。The gRPC Service template is selected.
    • 選取 [建立]。Select Create.

執行服務Run the service

  • 按 Ctrl+F5 即可執行而不使用偵錯工具。Press Ctrl+F5 to run without the debugger.

    Visual Studio 會顯示下列對話方塊:Visual Studio displays the following dialog:

    此專案設定為使用 SSL。

    如果您信任 IIS Express SSL 憑證,請選取 [是]。Select Yes if you trust the IIS Express SSL certificate.

    此時會顯示下列對話方塊:The following dialog is displayed:

    安全性警告對話方塊

    若您同意信任開發憑證,請選取 [是]。Select Yes if you agree to trust the development certificate.

    如需有關信任 Firefox 瀏覽器的詳細資訊,請參閱 firefox SEC_ERROR_INADEQUATE_KEY_USAGE 憑證錯誤For information on trusting the Firefox browser, see Firefox SEC_ERROR_INADEQUATE_KEY_USAGE certificate error.

    Visual Studio 會啟動 IIS Express,並執行應用程式。Visual Studio starts IIS Express and runs the app. 位址列會顯示 localhost:port#,而不是類似於 example.com 的內容。The address bar shows localhost:port# and not something like example.com. 這是因為 localhost 是本機電腦的標準主機名稱。That's because localhost is the standard hostname for the local computer. Localhost 只會為來自本機電腦的 Web 要求提供服務。Localhost only serves web requests from the local computer. 當 Visual Studio 建立 Web 專案時,會為網頁伺服器使用隨機連接埠。When Visual Studio creates a web project, a random port is used for the web server.

該記錄會顯示正在接聽 https://localhost:5001 的服務。The logs show the service listening on https://localhost:5001.

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

注意

gRPC 範本已設為使用傳輸層安全性 (TLS)The gRPC template is configured to use Transport Layer Security (TLS). gRPC 用戶端需要使用 HTTPS 來呼叫伺服器。gRPC clients need to use HTTPS to call the server.

macOS 不支援具有 TLS 的 ASP.NET Core gRPC。macOS doesn't support ASP.NET Core gRPC with TLS. 您需要額外的組態才能在 macOS 上成功執行 gRPC 服務。Additional configuration is required to successfully run gRPC services on macOS. 如需詳細資訊,請參閱無法在 macOS 上啟動 ASP.NET Core gRPC 應用程式For more information, see Unable to start ASP.NET Core gRPC app on macOS.

檢查專案檔Examine the project files

GrpcGreeter 專案檔:GrpcGreeter project files:

  • 歡迎Protos/歡迎. proto 檔案定義 Greeter gRPC,並用來產生 gRPC 伺服器資產。greet.proto: The Protos/greet.proto file defines the Greeter gRPC and is used to generate the gRPC server assets. 如需詳細資訊,請參閱 gRPC 簡介For more information, see Introduction to gRPC.
  • Services 資料夾:包含服務的執行 GreeterServices folder: Contains the implementation of the Greeter service.
  • appSettings.json:包含設定資料,例如 Kestrel 所使用的通訊協定。appSettings.json: Contains configuration data, such as protocol used by Kestrel. 如需詳細資訊,請參閱ASP.NET Core 的設定For more information, see ASP.NET Core 的設定.
  • Program.cs:包含 gRPC 服務的進入點。Program.cs: Contains the entry point for the gRPC service. 如需詳細資訊,請參閱ASP.NET Core 中的 .NET 泛型主機For more information, see ASP.NET Core 中的 .NET 泛型主機.
  • Startup.cs:包含設定應用程式行為的程式碼。Startup.cs: Contains code that configures app behavior. 如需詳細資訊,請參閱應用程式啟動For more information, see App startup.

在 .NET 主控台應用程式中建立 gRPC 用戶端Create the gRPC client in a .NET console app

  • 開啟第二個 Visual Studio 執行個體,並選取 [建立新專案]****。Open a second instance of Visual Studio and select Create a new project.
  • 在 [建立新專案]**** 對話方塊中,選取 [主控台應用程式 (.NET Core)]**** 並選取 [下一步]****。In the Create a new project dialog, select Console App (.NET Core) and select Next.
  • 在 [ 專案名稱 ] 文字方塊中,輸入 GrpcGreeterClient ,然後選取 [ 建立]。In the Project name text box, enter GrpcGreeterClient and select Create.

新增必要套件Add required packages

gRPC 用戶端專案需要下列套件:The gRPC client project requires the following packages:

  • Grpc.Net.Client,包含 .NET Core 用戶端。Grpc.Net.Client, which contains the .NET Core client.
  • Google.Protobuf,包含 C# 的 protobuf 訊息 API。Google.Protobuf, which contains protobuf message APIs for C#.
  • Grpc.Tools,包含 protobuf 檔案的 C# 工具支援。Grpc.Tools, which contains C# tooling support for protobuf files. 執行階段不需要工具套件,因此相依性會標示為 PrivateAssets="All"The tooling package isn't required at runtime, so the dependency is marked with PrivateAssets="All".

使用套件管理員主控台 (PMC) 或管理 NuGet 套件來安裝套件。Install the packages using either the Package Manager Console (PMC) or Manage NuGet Packages.

安裝套件的 PMC 選項PMC option to install packages

  • 從 Visual Studio 中,選取 [工具] > NuGet 封裝管理員 > 封裝管理員主控台From Visual Studio, select Tools > NuGet Package Manager > Package Manager Console

  • 從 [套件管理員主控台]**** 視窗,執行 cd GrpcGreeterClient 以變更包含 GrpcGreeterClient.csproj 檔案之資料夾的目錄。From the Package Manager Console window, run cd GrpcGreeterClient to change directories to the folder containing the GrpcGreeterClient.csproj files.

  • 執行下列命令:Run the following commands:

    Install-Package Grpc.Net.Client
    Install-Package Google.Protobuf
    Install-Package Grpc.Tools
    

管理 NuGet 套件選項來安裝套件Manage NuGet Packages option to install packages

  • 方案總管 > 管理 NuGet 套件] 中的專案上按一下滑鼠右鍵Right-click the project in Solution Explorer > Manage NuGet Packages
  • 選取 [瀏覽] 索引標籤。Select the Browse tab.
  • 在搜尋方塊中輸入 Grpc.Net.ClientEnter Grpc.Net.Client in the search box.
  • 從 [瀏覽]**** 索引標籤選取 [Grpc.Net.Client]**** 套件,然後選取 [安裝]****。Select the Grpc.Net.Client package from the Browse tab and select Install.
  • Google.ProtobufGrpc.Tools 重複進行。Repeat for Google.Protobuf and Grpc.Tools.

新增 greet.protoAdd greet.proto

  • 在 gRPC 用戶端專案中建立 [Protos]** 資料夾。Create a Protos folder in the gRPC client project.

  • Protos\greet.proto 檔案從 gRPC Greeter 服務複製到 gRPC 用戶端專案。Copy the Protos\greet.proto file from the gRPC Greeter service to the gRPC client project.

  • 將檔案內的命名空間更新 greet.proto 為專案的命名空間:Update the namespace inside the greet.proto file to the project's namespace:

    option csharp_namespace = "GrpcGreeterClient";
    
  • 編輯 GrpcGreeterClient.csproj 專案檔:Edit the GrpcGreeterClient.csproj project file:

    以滑鼠右鍵按一下專案,然後選取 [編輯專案檔]****。Right-click the project and select Edit Project File.


  • 新增具有代表 greet.proto 檔案之 <Protobuf> 元素的項目群組:Add an item group with a <Protobuf> element that refers to the greet.proto file:

    <ItemGroup>
      <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
    </ItemGroup>
    

建立 Greeter 用戶端Create the Greeter client

建置專案,以便在 GrpcGreeter 命名空間中建立類型。Build the project to create the types in the GrpcGreeter namespace. GrpcGreeter 類型會自動由建置處理序產生。The GrpcGreeter types are generated automatically by the build process.

利用下列程式碼,更新 gRPC 用戶端 Program.cs 檔案:Update the gRPC client Program.cs file with the following code:

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Grpc.Net.Client;

namespace GrpcGreeterClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // The port number(5001) must match the port of the gRPC server.
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            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();
        }
    }
}

Program.cs 包含 gRPC 用戶端的進入點和邏輯。Program.cs contains the entry point and logic for the gRPC client.

Greeter 用戶端建立者:The Greeter client is created by:

  • 具現化包含建立與 gRPC 服務連線資訊的 GrpcChannelInstantiating a GrpcChannel containing the information for creating the connection to the gRPC service.
  • 使用 GrpcChannel 建構 Greeter 用戶端:Using the GrpcChannel to construct the Greeter client:
static async Task Main(string[] args)
{
    // The port number(5001) must match the port of the gRPC server.
    using var channel = GrpcChannel.ForAddress("https://localhost:5001");
    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 方法。The Greeter client calls the asynchronous SayHello method. 顯示 SayHello 呼叫的結果:The result of the SayHello call is displayed:

static async Task Main(string[] args)
{
    // The port number(5001) must match the port of the gRPC server.
    using var channel = GrpcChannel.ForAddress("https://localhost:5001");
    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 用戶端Test the gRPC client with the gRPC Greeter service

  • 在 Greeter 服務中按下 Ctrl+F5,在不啟動偵錯工具的情況下啟動伺服器。In the Greeter service, press Ctrl+F5 to start the server without the debugger.
  • GrpcGreeterClient 專案中按下 Ctrl+F5,在不啟動偵錯工具的情況下啟動用戶端。In the GrpcGreeterClient project, press Ctrl+F5 to start the client without the debugger.

用戶端會以包含其名稱 GreeterClient的訊息,將問候語傳送至服務。The client sends a greeting to the service with a message containing its name, GreeterClient. 該服務會傳送 "Hello GreeterClient" 訊息做為回應。The service sends the message "Hello GreeterClient" as a response. "Hello GreeterClient" 回應會顯示在命令提示字元中:The "Hello GreeterClient" response is displayed in the command prompt:

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

gRPC 服務會將成功呼叫的詳細資料,記錄在會寫入命令提示字元的記錄中:The gRPC service records the details of the successful call in the logs written to the command prompt:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
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:5001/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

注意

此文章中的程式碼需要 ASP.NET Core HTTPS 開發憑證來保護 gRPC 服務。The code in this article requires the ASP.NET Core HTTPS development certificate to secure the gRPC service. 如果 .NET gRPC 用戶端因訊息 The remote certificate is invalid according to the validation procedure. 或而失敗 The SSL connection could not be established. ,則開發憑證不受信任。If the .NET gRPC client fails with the message The remote certificate is invalid according to the validation procedure. or The SSL connection could not be established., the development certificate isn't trusted. 若要修正此問題,請參閱 使用未受信任/不正確憑證呼叫 gRPC 服務To fix this issue, see Call a gRPC service with an untrusted/invalid certificate.

警告

Azure App Service 或 IIS 上目前不支援ASP.NET Core gRPCASP.NET Core gRPC is not currently supported on Azure App Service or IIS. Http.Sys 的 HTTP/2 執行不支援 gRPC 所依賴的 HTTP 回應尾端標頭。The HTTP/2 implementation of Http.Sys does not support HTTP response trailing headers which gRPC relies on. 如需詳細資訊,請參閱 此 GitHub 問題For more information, see this GitHub issue.

後續步驟Next steps