You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中使用API密钥初始化GCP MetricServiceClient

如何用API密钥初始化Google Cloud Metric Service Client(Google.Cloud.Monitoring.V3.MetricServiceClient)

问题背景

本地C#应用需初始化Google.Cloud.Monitoring.V3.MetricServiceClient,使用Application Default Credentials(ADC)执行gcloud auth application-default login的方式可正常工作,但存在两个局限:

  • 凭证会过期
  • 部署到客户端时需手动运行gcloud命令,操作不便

尝试使用API密钥初始化,但发现基于BaseClientService.Initializer创建DiscoveryService的方式不适用:MetricService是静态类无法实例化,报错Error CS0712 Cannot create an instance of the static class 'MetricService'。

解决方案

MetricServiceClient属于gRPC生成的客户端SDK,和基于Discovery文档的MetricService不是同一套体系,需通过MetricServiceClientBuilder来配置API密钥:

用API密钥初始化客户端

using Grpc.Core;
using Google.Cloud.Monitoring.V3;

// 替换为你的API密钥和项目ID
string apiKey = "YOUR_API_KEY";
string projectId = "YOUR_PROJECT_ID";

// 通过Builder配置API密钥并构建客户端
MetricServiceClient client = new MetricServiceClientBuilder
{
    ApiKey = apiKey
}.Build();

// 执行原有请求逻辑
ListMetricDescriptorsRequest request = new ListMetricDescriptorsRequest
{
    ProjectName = new ProjectName(projectId),
    Filter = "metric.type = starts_with(\"custom.googleapis.com/\")"
};

var result = client.ListMetricDescriptors(request);

补充:服务账号初始化方案(更推荐)

API密钥适合公开数据的无权限访问场景,若需权限控制,更推荐使用服务账号:

using Google.Cloud.Monitoring.V3;

string serviceAccountKeyPath = "path/to/your-service-account-key.json";
string projectId = "YOUR_PROJECT_ID";

MetricServiceClient client = new MetricServiceClientBuilder
{
    CredentialsPath = serviceAccountKeyPath
}.Build();

// 后续请求逻辑同上

内容的提问来源于stack exchange,提问作者Turgay Senlet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 05:39:52