メインコンテンツまでスキップ

C#

gRPC ガイドに従って Platform 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 パスは含めません。