简体   繁体   English

我对给定字符串的翻译无法使用 AzureApi

[英]My translation of a given string doesn't work using AzureApi

I want to translate a given string to a specific language and print the translation to console, but my console prints nothing, I am also trying to catch some error, but my console still prints nothing, anyone know why?我想将给定的字符串翻译成特定的语言并将翻译打印到控制台,但我的控制台什么都不打印,我也试图捕获一些错误,但我的控制台仍然什么都不打印,有人知道为什么吗? Here are my headers:这是我的标题:

using Newtonsoft.Json;
using System.Net.Http;
using NPOI.SS.Formula.Functions;

I have defined the necessary key and region and url attribute inside class block, but it just won't work like this:我已经在类块中定义了必要的键、区域和 url 属性,但它不会像这样工作:

public const string subscriptionKey = "mykey";
public const string region = "myregion";
public const string endpoint="https://api.cognitive.microsofttranslator.com/";

mykey consists of my subscription key and myregion consists of my region mykey 包含我的订阅密钥,myregion 包含我所在的地区

Here is my main:这是我的主要内容:

TranslateString();

Here is my implementation of method TranslateString这是我对方法 TranslateString 的实现

public static async void TranslateString()
        {
            string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
            string xmlString = "Hello , welcome";
            try
            {
                object[] body = new object[] { new { Text = xmlString } };
                var requestBody = 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", subscriptionKey);

                    request.Headers.Add("Ocp-Apim-Subscription-Region", region);


                    HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("Success , translated text:");
                        string result = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(result);
                    }
                    else
                    {
                        Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex.Message);
            }

Here is your code with minimal changes to make it produce an output.这是您的代码,只需进行最少的更改即可生成输出。 The relevant change is for TranslateString() to return a Task, so that the main thread waits for the async call to complete.相关的变化是 TranslateString() 返回一个 Task,以便主线程等待异步调用完成。 Another option would have been to make this a synchronous call.另一种选择是将其设为同步调用。

This uses the.Net built-in Json serializer instead of Newtonsoft for simplicity.为简单起见,这里使用 .Net 内置的 Json 序列化程序而不是 Newtonsoft。

This compiles as is using.Net7 with C#10, and your key and region filled in.这将按使用 .Net7 和 C#10 的方式进行编译,并填写您的密钥和区域。

using System.Net;
using System.Text;
using System.Text.Json;

const string subscriptionKey = "mykey";
const string region = "myregion";
const string endpoint = "https://api.cognitive.microsofttranslator.com/";


Console.WriteLine("Program Start");
await TranslateString();



static async Task TranslateString()
{
    string route = "translate?api-version=3.0&from=en&to=fr&to=zu";
    string xmlString = "Hello , welcome";
    try
    {
        object[] body = new object[] { new { Text = xmlString } };
        var requestBody = JsonSerializer.Serialize(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", subscriptionKey);

            request.Headers.Add("Ocp-Apim-Subscription-Region", region);


            HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Success , translated text:");
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine("Error: " + response.StatusCode + " " + response.ReasonPhrase);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error:" + ex.Message);
    }
}

The output is:输出是:

Program Start
Success , translated text:
[{"translations":[{"text":"Bonjour , bienvenue","to":"fr"},{"text":"Sawu , wamukelekile","to":"zu"}]}]

You will need to add deserializing the output.您将需要添加反序列化输出。

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

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