简体   繁体   English

始终使用 Microsoft Translator 获得 401

[英]Always getting 401 with Microsoft Translator

have done the following steps:已完成以下步骤:

  1. Generated the Translator API Key in Azure Portal.在 Azure 门户中生成了 Translator API 密钥。
  2. Tried using Ocp-Apim-Subscription-Key with Global end point - (api.cognitive.microsofttranslator.com)尝试使用具有全局端点的 Ocp-Apim-Subscription-Key - (api.cognitive.microsofttranslator.com)
  3. Tried using Ocp-Apim-Subscription-Region with Regional end point (api-eur.cognitive.microsofttranslator.com)尝试使用具有区域端点的 Ocp-Apim-Subscription-Region (api-eur.cognitive.microsofttranslator.com)
  4. Regenerated the security keys as well.也重新生成了安全密钥。

I have followed the quick start sample to the word - https://docs.microsoft.com/en-us/azure/cognitive-services/Translator/quickstart-translate?pivots=programming-language-csharp我已按照快速入门示例进行操作 - https://docs.microsoft.com/en-us/azure/cognitive-services/Translator/quickstart-translate?pivots=programming-language-csharp

However, always getting 401 as the response.但是,总是得到 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);
                }
            }
        }

I noticed the same errors when trying to run that sample.我在尝试运行该示例时注意到了同样的错误。 I was able to get this to work with a few changes.我能够通过一些更改使其工作。

First: Change your endpoint to https://api.cognitive.microsofttranslator.com/ .首先:将您的端点更改为https://api.cognitive.microsofttranslator.com/

Next: I noticed you commented out the Ocp-Apim-Subscription-Key header. Next: 我注意到您注释掉了Ocp-Apim-Subscription-Key header。 You should uncomment that, as that is required (and is correct, the way you had it).您应该取消注释,因为这是必需的(并且是正确的,您拥有它的方式)。

Next: Add the Ocp-Apim-Subscription-Region header.下一步:添加Ocp-Apim-Subscription-Region header。 I see you already attempted to add that, but you tried setting it to your subscription key.我看到您已经尝试添加它,但您尝试将其设置为您的订阅密钥。 Instead, set this to your Cognitive Service's specific region value (you can find this value in the portal, just under your keys and endpoint).相反,请将其设置为您的认知服务的特定区域值(您可以在门户中找到该值,就在您的密钥和端点下)。 Mine, for instance, is eastus .例如,我的是eastus

At this point, you should be able to make a successful call.此时,您应该能够成功拨打电话。 I verified this with my own Cognitive Services instance.我用自己的认知服务实例验证了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM