简体   繁体   中英

Always getting 401 with Microsoft Translator

have done the following steps:

  1. Generated the Translator API Key in Azure Portal.
  2. Tried using Ocp-Apim-Subscription-Key with Global end point - (api.cognitive.microsofttranslator.com)
  3. Tried using Ocp-Apim-Subscription-Region with Regional end point (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

However, always getting 401 as the response.

    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/ .

Next: I noticed you commented out the 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. 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 .

At this point, you should be able to make a successful call. I verified this with my own Cognitive Services instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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