C#
首先阅读 gRPC 指南,创建平台 API 令牌并下载 platform.proto。在包含此文件的目录中运行以下命令。
创建 .NET 控制台项目:
dotnet new console -n ReconstructExample
进入项目目录:
cd ReconstructExample
添加 gRPC 客户端包:
dotnet add package Grpc.Net.Client
dotnet add package Grpc.Tools
dotnet add package Google.Protobuf
将下载的 platform.proto 复制到 ReconstructExample 目录。
将以下项目添加至项目的 .csproj 文件。Grpc.Tools 会在构建时生成客户端:
<ItemGroup>
<Protobuf Include="platform.proto" GrpcServices="Client" />
</ItemGroup>
在 Program.cs 中使用生成的类型:
using Cr.Reconstruct.External.Grpc;
using Grpc.Core;
using Grpc.Net.Client;
var token = Environment.GetEnvironmentVariable("CR_RECONSTRUCT_API_TOKEN")
?? throw new InvalidOperationException("Set CR_RECONSTRUCT_API_TOKEN.");
var address = Environment.GetEnvironmentVariable("CR_RECONSTRUCT_GRPC_URL")
?? "https://reconstruct.dev";
using var channel = GrpcChannel.ForAddress(address);
var client = new PlatformService.PlatformServiceClient(channel);
var headers = new Metadata { { "authorization", $"Bearer {token}" } };
var page = await client.ListCatalogsAsync(
new ListCatalogsRequest { PageSize = 10 }, headers, deadline: DateTime.UtcNow.AddSeconds(10));
foreach (var catalog in page.Catalogs)
{
var detail = await client.GetCatalogAsync(
new GetCatalogRequest { CatalogId = catalog.CatalogId }, headers);
Console.WriteLine($"{detail.CatalogId}: {detail.Description}");
}
运行 dotnet run。原生 gRPC 通道使用 HTTPS 的主机和端口,不包含 REST 路径 /api/v1/platform。