C# 始终使用Microsoft Translator获得401

C# 始终使用Microsoft Translator获得401,c#,microsoft-translator,C#,Microsoft Translator,已完成以下步骤: 已在Azure Portal中生成转换器API密钥 已尝试将Ocp Apim订阅密钥与全局端点一起使用-(api.cognitive.microsofttranslator.com) 已尝试使用Ocp Apim订阅区域和区域端点(api eur.cognitive.microsofttranslator.com) 还重新生成了安全密钥 我已按照快速入门示例中的单词- 然而,总是得到401作为回应 private static readonly string subscr

已完成以下步骤:

  • 已在Azure Portal中生成转换器API密钥
  • 已尝试将Ocp Apim订阅密钥与全局端点一起使用-(api.cognitive.microsofttranslator.com)
  • 已尝试使用Ocp Apim订阅区域和区域端点(api eur.cognitive.microsofttranslator.com)
  • 还重新生成了安全密钥
  • 我已按照快速入门示例中的单词-

    然而,总是得到401作为回应

        private static readonly string subscriptionKey = "<KEY>";
        private static readonly string endpoint = "https://api-eur.cognitive.microsofttranslator.com/";
    
        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);
            }
        }
        static async Task Main(string[] args)
        {
            string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th";
            Console.Write("Type the phrase you'd like to translate? ");
            string textToTranslate = Console.ReadLine();
            await TranslateTextRequest(subscriptionKey, endpoint, route, textToTranslate);
            Console.WriteLine("Press any key to continue.");
            Console.ReadKey();
        }
      
        static public async Task TranslateTextRequest(string subscriptionKey, string endpoint, string route, string inputText)
        {
            object[] body = new object[] { new { Text = inputText } };
            var requestBody = JsonConvert.SerializeObject(body);
    
            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                request.Method = HttpMethod.Post;
                // Construct the URI and add headers.
                request.RequestUri = new Uri(endpoint + route);
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                //request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
                request.Headers.Add("Ocp-Apim-Subscription-Region", subscriptionKey);
    
                // Send the request and get response.
                HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
                // Read response as a string.
                string result = await response.Content.ReadAsStringAsync();
                // Deserialize the response using the classes created earlier.
                TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
                // Iterate over the deserialized results.
                foreach (TranslationResult o in deserializedOutput)
                {
                    // Print the detected input language and confidence score.
                    Console.WriteLine("Detected input language: {0}\nConfidence score: {1}\n", o.DetectedLanguage.Language, o.DetectedLanguage.Score);
                    // Iterate over the results and print each translation.
                    foreach (Translation t in o.Translations)
                    {
                        Console.WriteLine("Translated to {0}: {1}", t.To, t.Text);
                    }
                }
            }
    
    私有静态只读字符串subscriptionKey=”“;
    私有静态只读字符串终结点=”https://api-eur.cognitive.microsofttranslator.com/";
    静态程序()
    {
    if(null==subscriptionKey)
    {
    抛出新异常(“请设置/导出环境变量:“+key\u var”);
    }
    if(null==端点)
    {
    抛出新异常(“请设置/导出环境变量:”+endpoint_var);
    }
    }
    静态异步任务主(字符串[]args)
    {
    string route=“/translate?api version=3.0&to=de&to=it&to=ja&to=th”;
    Console.Write(“键入您要翻译的短语?”);
    字符串textToTranslate=Console.ReadLine();
    等待TranslateTextRequest(subscriptionKey、端点、路由、textToTranslate);
    Console.WriteLine(“按任意键继续”);
    Console.ReadKey();
    }
    静态公共异步任务TranslateTextRequest(字符串subscriptionKey、字符串端点、字符串路由、字符串inputText)
    {
    object[]body=new object[]{new{Text=inputText}};
    var requestBody=JsonConvert.serialized对象(body);
    使用(var client=new HttpClient())
    使用(var request=new HttpRequestMessage())
    {
    request.Method=HttpMethod.Post;
    //构造URI并添加头。
    request.RequestUri=新Uri(端点+路由);
    request.Content=newstringcontent(requestBody,Encoding.UTF8,“application/json”);
    //添加(“Ocp Apim订阅密钥”,subscriptionKey);
    添加(“Ocp Apim订阅区域”,subscriptionKey);
    //发送请求并获得响应。
    HttpResponseMessage response=await client.SendAsync(请求).ConfigureAwait(错误);
    //将响应读取为字符串。
    字符串结果=wait response.Content.ReadAsStringAsync();
    //使用前面创建的类反序列化响应。
    TranslationResult[]反序列化输出=JsonConvert.DeserializeObject(结果);
    //迭代反序列化的结果。
    foreach(反序列化输出中的TranslationResult o)
    {
    //打印检测到的输入语言和置信度分数。
    WriteLine(“检测到的输入语言:{0}\n可信度分数:{1}\n”,o.DetectedLanguage.language,o.DetectedLanguage.score);
    //迭代结果并打印每个翻译。
    foreach(o.Translations中的t翻译)
    {
    WriteLine(“翻译成{0}:{1}”,t.to,t.Text);
    }
    }
    }
    
    在尝试运行该示例时,我注意到了相同的错误。通过一些更改,我可以使其正常工作

    第一:将端点更改为
    https://api.cognitive.microsofttranslator.com/

    下一步:我注意到您注释掉了
    Ocp-Apim-Subscription-Key
    标题。您应该取消注释,因为这是必需的(并且是正确的,您的方式是正确的)

    下一步:添加
    Ocp Apim Subscription Region
    标题。我看到您已经尝试添加该标题,但您尝试将其设置为订阅密钥。相反,请将其设置为认知服务的特定区域值(您可以在门户中的密钥和端点下找到该值).例如,我的是
    eastus

    此时,您应该能够成功拨打电话。我用自己的认知服务实例验证了这一点