I am using the ‘AzureAITranslator’ API for text translation. After a few days of usage, I am getting this error:
StatusCode: 401, ReasonPhrase: 'Unauthorized'
I tried the following steps to get it to work but still getting the 'Unauthorized' error.
- I initially used Key 1 for text translation. I changed it to Key 2.
- Regenerated both the keys.
Following is the code being used:
private static string key ="-------";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
private static readonly string region = "-------";
public static async Task<string> TranslateString(string from, string to, string translatedText)
{
string route = "translate?api-version=3.0&from=" + from + "&to=" + to;
string xmlString = translatedText;
string result = "" ;
try
{
object[] body = new object[] { new { Text = xmlString } };
var requestBody = JsonConvert.SerializeObject(body);
JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", region);
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success , translated text:");
result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
else
{
Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}
return result;
}
The
I faced a similar issue last week but was able to get it to work by creating a new translator API.
Could you please let me know what could be the reason for the Unauthorised access error?