[英]Always getting 401 with Microsoft Translator
已完成以下步驟:
我已按照快速入門示例進行操作 - 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/
。
Next: 我注意到您注釋掉了Ocp-Apim-Subscription-Key
header。 您應該取消注釋,因為這是必需的(並且是正確的,您擁有它的方式)。
下一步:添加Ocp-Apim-Subscription-Region
header。 我看到您已經嘗試添加它,但您嘗試將其設置為您的訂閱密鑰。 相反,請將其設置為您的認知服務的特定區域值(您可以在門戶中找到該值,就在您的密鑰和端點下)。 例如,我的是eastus
。
此時,您應該能夠成功撥打電話。 我用自己的認知服務實例驗證了這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.