Translate Text Into Multiple Languages Using Translator Text API With ASP.NET Core And C#

Introduction
 
In this article, we are going to learn how to translate text into multiple languages using an important Cognitive Services API called Microsoft Translate Text API (one of the Language APIs). It’s a simple cloud-based machine translation service and obviously, we can test it through simple Rest API call. Microsoft is using a new standard for high-quality AI-powered machine translations known as Neural Machine Translation (NMT).
 
Translate Text into multiple languages using Translator Text API With Asp.Net Core & C#
Pic source : https://www.microsoft.com/en-us/translator/business/machine-translation/#whatmachine
 
You can also refer to the following articles on Cognitive Service.
Prerequisites
  1. Subscription key ( Azure Portal )
  2. Visual Studio 2015 or 2017
Translator Text API
 
First, we need to log into the Azure Portal with our Azure credentials. Then, we need to create an Azure Translator Text API in the Azure portal. So please click on the "Create a resource" on the left top menu and search "Translator Text" in the search bar on the right side window or on the top of Azure Marketplace.
 
Translate Text into multiple languages using Translator Text API With Asp.Net Core & C#
 
Click on the “Create” button to create Translator Text API.
 
Translate Text into multiple languages using Translator Text API With Asp.Net Core & C#
 
Provision a Translator Text Subscription Key
 
After clicking "Create", it will open another window. There, we need to provide the basic information about Translator Text API.
 
Translate Text into multiple languages using Translator Text API With Asp.Net Core & C#
  • Name - Name of the Translator Text API ( Eg. TranslatorTextApp ).
  • Subscription - We can select our Azure subscription for Translator Text API creation.
  • Location - We can select our location of a resource group. The best thing is we can choose a location closest to our customer.
  • Pricing tier - Select an appropriate pricing tier for our requirement.
  • Resource group - We can create a new resource group or choose from an existing one.
Now click on the "TranslatorTextApp" in the dashboard page and it will redirect to the detailed page of TranslatorTextApp ( "Overview" ). Here, we can see the "Keys" ( Subscription key details ) menu on the left side panel. Then click on the "Keys" menu and it will open the Subscription Keys details. We can use any of the subscription keys or regenerate the given key for text translation using Microsoft Translator Text API.
 
Translate Text into multiple languages using Translator Text API With Asp.Net Core & C# 
 
Language Request URL
 
The following request URL gets the set of languages currently supported by other operations of the Microsoft Translator Text API.
"https://api.cognitive.microsofttranslator.com/languages?api-version=3.0"
 
Endpoint
 
The version of the API requested by the client and the Value must be 3.0 and also we can include query parameters and request headers in the following endPoint used in our application.
 
"https://api.cognitive.microsofttranslator.com/translate?api-version=3.0"
 
Mandatory required parameters in the query string are "api-version" and "to" . The "api-version" value must be "3.0" as per the current documentation. "to" is the language code parameter used for translating the entered text into the desired language.
The mandatory request headers are "authorization header" and "Content-Type". We can pass our subscription key into the "authorization header" and the simplest way is to pass our Azure secret key to the Translator service using request header "Ocp-Apim-Subscription-Key".
 
Index.html
 
The following HTML contains the binding methodology that we have used in our application by using the latest Tag helpers of ASP.Net Core.
 
Translate Text into multiple languages using Translator Text API With Asp.Net Core & C# 
site.js
 
The following ajax call will trigger for each drop-down index change in the language selection using the drop-down list.
  1. $(function () {  
  2.     $(document)  
  3.         .on('change''#ddlLangCode'function () {  
  4.             var languageCode = $(this).val();  
  5.             var enterText = $("#enterText").val();  
  6.             if (1 <= $("#enterText").val().trim().length && languageCode != "NA") {  
  7.     
  8.                 $('#enterText').removeClass('redBorder');  
  9.     
  10.                 var url = '/Home/Index';  
  11.                 var dataToSend = { "LanguageCode": languageCode, "Text": enterText };  
  12.                 dataType: "json",  
  13.                     $.ajax({  
  14.                         url: url,  
  15.                         data: dataToSend,  
  16.                         type: 'POST',  
  17.                         success: function (response) {  
  18.                             //update control on View  
  19.                             var result = JSON.parse(response);  
  20.                             var translatedText = result[0].translations[0].text;  
  21.                             $('#translatedText').val(translatedText);  
  22.                         }  
  23.                     })  
  24.             }  
  25.             else {  
  26.                 $('#enterText').addClass('redBorder');  
  27.                 $('#translatedText').val("");  
  28.             }  
  29.         });  
  30. });  
Interface
 
The "ITranslateText" contains one signature for translating text content based on the given input. So we have injected this interface in the ASP.NET Core "Startup.cs" class as an "AddTransient".
  1. using System.Threading.Tasks;  
  2.     
  3. namespace TranslateTextApp.Business_Layer.Interface  
  4. {  
  5.     interface ITranslateText  
  6.     {  
  7.         Task<string> Translate(string uri, string text, string key);  
  8.     }  
  9. }  
Translator Text API Service
 
We can add the valid Translator Text API Subscription Key into the following code.
  1. using Newtonsoft.Json;  
  2. using System;  
  3. using System.Net.Http;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using TranslateTextApp.Business_Layer.Interface;  
  7.     
  8. namespace TranslateTextApp.Business_Layer  
  9. {  
  10.     public class TranslateTextService : ITranslateText  
  11.     {  
  12.         ///  
  13. <summary>  
  14.         /// Translate the given text in to selected language.  
  15.         /// </summary>  
  16.     
  17.         /// <param name="uri">Request uri</param>  
  18.         /// <param name="text">The text is given for translation</param>  
  19.         /// <param name="key">Subscription key</param>  
  20.         /// <returns></returns>  
  21.         public async Task<string> Translate(string uri, string text, string key)  
  22.         {  
  23.             System.Object[] body = new System.Object[] { new { Text = text } };  
  24.             var requestBody = JsonConvert.SerializeObject(body);  
  25.                 
  26.             using (var client = new HttpClient())  
  27.             using (var request = new HttpRequestMessage())  
  28.             {  
  29.                 request.Method = HttpMethod.Post;  
  30.                 request.RequestUri = new Uri(uri);  
  31.                 request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");  
  32.                 request.Headers.Add("Ocp-Apim-Subscription-Key", key);  
  33.     
  34.                 var response = await client.SendAsync(request);  
  35.                 var responseBody = await response.Content.ReadAsStringAsync();  
  36.                 dynamic result = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented);  
  37.                     
  38.                 return result;  
  39.             }  
  40.         }  
  41.     }  
  42. }  
API Response – Based on the given text
 
The successful JSON response.
  1. [  
  2.   {  
  3.     "detectedLanguage": {  
  4.       "language""en",  
  5.       "score": 1.0  
  6.     },  
  7.     "translations": [  
  8.       {  
  9.         "text""सफलता à¤•à¤¾ à¤•à¥‹à¤ˆ à¤¶à¤¾à¤°à¥à¤Ÿà¤•à¤Ÿ à¤¨à¤¹à¥€à¤‚ à¤¹à¥‹à¤¤à¤¾",  
  10.         "to""hi"  
  11.       }  
  12.     ]  
  13.   }  
  14. ]  
Download
Output
 
The given text is translated into the desired language listed in the drop-down list using Microsoft Translator API.
 
Translate Text into multiple languages using Translator Text API With Asp.Net Core & C# 
Reference
Summary
 
From this article, we have learned to translate a text (typed in English) into different languages as per the API documentation using one of the important Cognitive Services API ( Translator Text API is a part of Language API ). I hope this article is useful for all Azure Cognitive Services API beginners.
 
See Also
 
You can download other ASP.NET Core source codes from MSDN Code, using the link, mentioned below.