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

C#调用Google翻译API v3遇权限拒绝,Python正常运行求解决方案

Google翻译API v3 C#权限拒绝问题解决思路

问题背景

使用Google API NuGet包调用Google翻译API v3时,抛出权限拒绝异常:

Grpc.Core.RpcException: 'Status(StatusCode="PermissionDenied", Detail="Cloud IAM permission 'cloudtranslate.languageDetectionModels.predict' denied. ")

但相同凭证的Python代码可正常运行,尝试两种C#客户端构建方式均无效。

核心解决思路

  • 修正Parent参数格式
    Google翻译API v3的Parent参数必须包含位置ID,格式为projects/{project-id}/locations/{location-id}(例如projects/my-project-name/locations/global)。当前代码仅传入projects/my-project-name,而Python客户端会默认使用global位置,C# gRPC客户端则要求明确指定,缺少位置会导致权限校验路径不匹配,触发拒绝。

  • 修复客户端构建代码逻辑
    第二种构建方式中,创建TranslationServiceClientBuilder后未使用其Build结果,而是重新调用TranslationServiceClient.Create(),等于未应用自定义凭证配置。正确代码如下:

    var credentialsPath = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
    var credential = GoogleCredential.FromFile(credentialsPath);
    
    _translationClient = new TranslationServiceClientBuilder() { 
        Credential = credential,
        Location = "global" // 可在此指定默认位置,或在请求Parent中明确
    }.Build();
    
  • 验证IAM权限范围
    确认服务账号的cloudtranslate.languageDetectionModels.predict权限已绑定到对应项目和位置,避免权限仅绑定特定位置但请求未匹配的情况。

  • 更新NuGet包版本
    检查Google.Cloud.Translation.V3包是否为最新版本,旧版本可能存在路径拼接或权限校验的兼容性问题,更新后重试。

  • 配置区域端点(按需)
    若使用非global位置,需在TranslationServiceClientBuilder中指定对应区域端点,例如:

    _translationClient = new TranslationServiceClientBuilder() { 
        Credential = credential,
        Endpoint = "europe-west3-translate.googleapis.com",
        Location = "europe-west3"
    }.Build();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:07:03