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

Microsoft Azure文本翻译器订阅密钥无法使用求助

问题分析与修复方案

我一眼就发现了导致订阅密钥无效的核心问题——你在环境变量的读取逻辑上完全搞反了,另外还有端点配置的错误,这两个问题共同触发了异常。

核心问题拆解

  1. 环境变量名与值混淆
    你把key_var直接设置成了订阅密钥的字符串值"b1f43a68dce24b0280360691ad68bc75",然后调用Environment.GetEnvironmentVariable(key_var),这意味着程序会去查找名为这个密钥字符串的环境变量,而不是读取存储密钥的环境变量。这显然不存在,所以subscriptionKey一直是null,触发了抛出的异常。
    同样的错误也出现在endpoint_var上——你把它设置成了具体的token端点URL,而不是环境变量的名称。

  2. 端点地址错误
    你配置的endpoint_var是STS令牌端点,但Translate Text API的调用应该使用Translator服务的基础端点(格式为https://<你的区域>.cognitiveservices.azure.com/),而不是令牌端点。

分步修复方案

步骤1:修正代码中的环境变量常量

把key_var和endpoint_var改成环境变量的名称(比如自定义的TRANSLATOR_SUBSCRIPTION_KEY和TRANSLATOR_ENDPOINT),而不是具体的密钥或URL值:

// 改成环境变量的名称,而非具体值
private const string key_var = "TRANSLATOR_SUBSCRIPTION_KEY";
private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var);
// 基础端点,不是STS令牌端点
private const string endpoint_var = "TRANSLATOR_ENDPOINT";
private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var);

步骤2:设置正确的环境变量

根据你的操作系统设置对应的环境变量:

  • Windows(命令提示符):
    set TRANSLATOR_SUBSCRIPTION_KEY=你的订阅密钥
    set TRANSLATOR_ENDPOINT=https://<你的区域>.cognitiveservices.azure.com/
    
  • Linux/macOS(终端):
    export TRANSLATOR_SUBSCRIPTION_KEY=你的订阅密钥
    export TRANSLATOR_ENDPOINT=https://<你的区域>.cognitiveservices.azure.com/
    
  • Visual Studio(项目内设置):右键项目 → 属性 → 调试 → 环境变量,添加上述两个键值对,这样每次调试都会自动加载。

步骤3:(可选)如果不想用环境变量,直接硬编码(不推荐,生产环境禁止)

如果你只是测试想跳过环境变量,可以直接赋值:

// 直接赋值订阅密钥和端点,注意生产环境不要这么做!
private static readonly string subscriptionKey = "b1f43a68dce24b0280360691ad68bc75";
private static readonly string endpoint = "https://<你的区域>.cognitiveservices.azure.com/";

然后删除原来的key_var、endpoint_var以及构造函数里的环境变量检查。

额外检查点

  • 确认你的订阅密钥属于Azure Translator Text服务,不是其他认知服务。
  • 确认端点的区域和你创建Translator服务时选择的区域一致(比如eastus、westeurope等)。
  • 检查你的密钥是否过期,或者是否在Azure门户中启用了服务。

修正后的完整代码片段(关键部分)

class Program
{
    // 环境变量名称,而非具体值
    private const string key_var = "TRANSLATOR_SUBSCRIPTION_KEY";
    private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var);
    private const string endpoint_var = "TRANSLATOR_ENDPOINT";
    private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var);

    static Program()
    {
        if (null == subscriptionKey)
        {
            throw new Exception("Please set/export the environment variable: " + key_var);
        }
        if (null == endpoint)
        {
            throw new Exception("Please set/export the environment variable: " + endpoint_var);
        }
    }

    // ... 其余代码保持不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:25:07