总是使用 Microsoft Translator 获得 401

Always getting 401 with Microsoft Translator

已完成以下步骤:

  1. 在 Azure 门户中生成了转换器 API 密钥。
  2. 尝试将 Ocp-Apim-Subscription-Key 与全局端点一起使用 - (api.cognitive.microsofttranslator.com)
  3. 尝试使用带有区域端点的 Ocp-Apim-Subscription-Region (api-eur.cognitive.microsofttranslator.com)
  4. 也重新生成了安全密钥。

我已经按照快速入门示例学习了单词 - https://docs.microsoft.com/en-us/azure/cognitive-services/Translator/quickstart-translate?pivots=programming-language-csharp

但是,总是收到 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);
                }
            }
        }

我在尝试 运行 该示例时注意到同样的错误。我能够通过一些更改使它工作。

首先:将您的端点更改为 https://api.cognitive.microsofttranslator.com/

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

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

至此,您应该可以拨打成功了。我用自己的认知服务实例验证了这一点。