教程:在 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.

先决条件Prerequisites

创建 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 :

    Visual Studio 中的“创建新项目”对话框

  • 将项目命名为 GrpcGreeter。Name the project GrpcGreeter. 将项目命名为“GrpcGreeter”非常重要,这样在复制和粘贴代码时命名空间就会匹配。It's important to name the project GrpcGreeter so the namespaces 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.comThe 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 项目时,为 Web 服务器使用随机端口。When Visual Studio creates a web project, a random port is used for the web server.

日志显示该服务正在侦听 https://localhost:5001The 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 不支持 ASP.NET Core gRPC 及 TLS。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:

  • greet.protoProtos/greet.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 文件夹:包含 Greeter 服务的实现。Services 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 消息。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.Client。Enter 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.

  • 从 gRPC Greeter 服务将 Protos\greet.proto 文件复制到 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 client 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:

  • 实例化 GrpcChannel,使其包含用于创建到 gRPC 服务的连接的信息。Instantiating 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 应用服务或 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