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

330 views Asked by At

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 :

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

Here is my main:

TranslateString();

Here is my implementation of method 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);
            }
1

There are 1 answers

2
Chris Wendt On

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. Another option would have been to make this a synchronous call.

This uses the .Net built-in Json serializer instead of Newtonsoft for simplicity.

This compiles as is using .Net7 with C#10, and your key and region filled in.

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.