在C#中使用Google API进行身份验证时,toChannelCredentials()
方法不存在的问题通常与gRPC和Google API客户端的版本或使用方式有关。以下是详细解析和解决方案:
toChannelCredentials()
可能是混淆了不同库的方法名(如Java客户端),或版本不兼容导致。using Google.Apis.Auth.OAuth2;
using Grpc.Auth;
using Grpc.Core;
// 1. 加载服务账号密钥文件
var credential = GoogleCredential.FromFile("service-account.json")
.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
// 2. 转换为gRPC的ChannelCredentials
ChannelCredentials channelCredentials = credential.ToChannelCredentials();
// 3. 创建gRPC通道
var channel = new Channel("speech.googleapis.com", 443, channelCredentials);
var client = new Speech.SpeechClient(channel);
var credential = GoogleCredential.GetApplicationDefault();
ChannelCredentials channelCredentials = credential.ToChannelCredentials();
Grpc.Auth
包或版本过低。GoogleCredential
未包含所需作用域(Scopes)。443
端口和正确域名:443
端口和正确域名:确保项目中包含以下NuGet包:
<PackageReference Include="Google.Apis.Auth" Version="1.60.0" />
<PackageReference Include="Grpc.Auth" Version="2.46.0" />
<PackageReference Include="Grpc.Core" Version="2.46.0" />
如果仍无法解决,可手动创建ChannelCredentials
:
var credential = GoogleCredential.FromFile("service-account.json");
var callCredentials = credential.ToCallCredentials();
ChannelCredentials channelCredentials = ChannelCredentials.Create(
new SslCredentials(), callCredentials);
通过以上步骤,可解决C#中Google API身份验证的凭证转换问题。若仍有异常,请检查密钥文件路径和网络策略(如代理设置)。
没有搜到相关的文章