已完成以下步骤:
(api.cognitive.microsofttranslator.com)
我遵循了快速启动示例到word - https://learn.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);
}
}
}发布于 2020-07-15 04:19:50
在尝试运行该示例时,我注意到了相同的错误。我做了几处改动才能让它发挥作用。
首先:将端点更改为https://api.cognitive.microsofttranslator.com/。
接下来:我注意到您注释掉了Ocp-Apim-Subscription-Key头。您应该取消评论,因为这是必要的(而且是正确的,您的方式)。
接下来:添加Ocp-Apim-Subscription-Region头。我看到您已经尝试添加了,但是您尝试将其设置为您的订阅密钥。相反,将其设置为您的认知服务的特定区域值(您可以在门户中找到此值,就在您的键和端点下面)。例如,我的就是eastus。
在这一点上,您应该能够作出一个成功的调用。我用自己的认知服务实例验证了这一点。
https://stackoverflow.com/questions/62767842
复制相似问题