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

ASP.NET Core生产环境调用Google Cloud Speech-to-Text API认证失败

ASP.NET Core部署生产环境后Google Speech-to-Text认证失败问题

部署ASP.NET Core Web应用到生产环境后,调用Google Cloud Speech-to-Text API时出现以下认证错误:

Status(StatusCode="Unauthenticated", Detail="Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.")

相关代码实现:

using Google.Cloud.Speech.V1;

namespace EventPrinter.Helpers
{
    public class GoogleTranscript
    {
        private readonly SpeechClient _speechClient;
        private readonly FileHelper _fileHelper;

        public GoogleTranscript(FileHelper fileHelper)
        {
            _fileHelper = fileHelper;
            string credentialPath = @$"{_fileHelper.BaseDirectory}\transcription\firebase-219721-333cab8c23c6.json";
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credentialPath);
            
            _speechClient = SpeechClient.Create();
        }

        public async Task<string> TranscribeAsync(string filePath)
        {
            try
            {
                var response = await _speechClient.RecognizeAsync(new RecognitionConfig
                {
                    Encoding = RecognitionConfig.Types.AudioEncoding.Mp3,
                    SampleRateHertz = 48000,
                    LanguageCode = "he-IL"
                }, RecognitionAudio.FromFile(filePath));

                var transcripts = response.Results
                    .SelectMany(result => result.Alternatives)
                    .Select(alternative => $"{alternative.Transcript}")
                    .ToList();

                return transcripts.Any() ? string.Join("\n", transcripts) : "No transcription available.";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error during transcription: {ex.Message}");
                throw;
            }
        }
    }
}

已尝试的排查操作:

  • 验证凭证文件在两个环境中位置正确
  • 确认在创建SpeechClient前已设置GOOGLE_APPLICATION_CREDENTIALS环境变量
  • 服务账号已配置Cloud Speech API Client角色
  • 打印环境变量和文件路径,确认其正确性
  • 生产环境无防火墙或网络限制阻止API访问

预期结果:生产环境使用与本地相同的凭证和配置,能成功完成API认证并转写音频。


问题原因排查与解决方案

1. 环境变量作用域限制

ASP.NET Core中Environment.SetEnvironmentVariable默认是进程级作用域,但生产环境(如IIS)的应用程序池可能存在上下文隔离,或者后续代码/系统环境覆盖了该变量。最可靠的方式是直接通过凭证文件初始化客户端,绕开环境变量:

修改构造函数中的客户端初始化代码:

public GoogleTranscript(FileHelper fileHelper)
{
    _fileHelper = fileHelper;
    string credentialPath = @$"{_fileHelper.BaseDirectory}\transcription\firebase-219721-333cab8c23c6.json";
    
    // 直接加载凭证文件并初始化客户端
    var credential = GoogleCredential.FromFile(credentialPath);
    _speechClient = new SpeechClientBuilder { Credential = credential }.Build();
}

2. 生产环境文件权限不足

生产环境中,应用程序的运行身份(如IIS的AppPoolIdentity)可能没有凭证文件的读取权限。需要:

  • 右键凭证文件 → 「属性」→ 「安全」
  • 添加应用程序池身份(或IIS_IUSRS组),并赋予读取权限

3. 路径解析的隐性问题

即使打印路径显示正确,生产环境的BaseDirectory可能指向非预期目录(比如IIS站点的bin目录而非根目录)。建议:

  • 打印完整的凭证文件绝对路径到日志(而非相对路径)
  • 确认文件存在且可被应用读取(可以尝试在代码中添加File.Exists(credentialPath)和File.ReadAllText(credentialPath)的日志输出,验证是否能正常读取)

4. 凭证文件完整性问题

重新上传凭证文件到生产环境,避免传输过程中文件损坏:

  • 对比本地和生产环境凭证文件的MD5哈希值,确保完全一致
  • 使用二进制传输模式(如FTP的Binary模式)上传文件

5. 云环境默认身份冲突

如果生产环境部署在Google Cloud服务(如GCE、GKE)上,实例可能默认使用内置服务账号,覆盖了你指定的凭证。此时需要:

  • 明确通过SpeechClientBuilder指定凭证(如方案1所示)
  • 或禁用实例的默认服务账号权限(如果不需要)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:40:21