Multi language support by Google Translate?

badcat 1 Reputation point
2021-08-27T09:52:54.947+00:00

Hi,

I want to convert any text in terms of the language of browser.

I wrote code snippets shown below.

Here is the code to get browser language code like "fr", "de", "en"

StringWithQualityHeaderValue preferredLanguage = null;
if (Request.Headers.AllKeys.Contains("Accept-Language"))
{
    preferredLanguage = Request.Headers["Accept-Language"]
        .Split(',')
        .Select(StringWithQualityHeaderValue.Parse)
        .OrderByDescending(s => s.Quality.GetValueOrDefault(1))
        .FirstOrDefault();
}

Here is my translate function shown below.

public string TranslateText(string input)
{
// Set the language from/to in the url (or pass it into this function)
string url = String.Format
("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
"tr", "de", Uri.EscapeUriString(input));
HttpClient httpClient = new HttpClient();
string result = httpClient.GetStringAsync(url).Result;
// Get all json data
var jsonData = new JavaScriptSerializer().Deserialize<List<dynamic>>(result);
// Extract just the first array element (This is the only data we are interested in)
var translationItems = jsonData[0];
// Translation Data
string translation = "";
// Loop through the collection extracting the translated objects
foreach (object item in translationItems)
{
// Convert the item array to IEnumerable
IEnumerable translationLineObject = item as IEnumerable;
// Convert the IEnumerable translationLineObject to a IEnumerator
IEnumerator translationLineString = translationLineObject.GetEnumerator();
// Get first object in IEnumerator
 translationLineString.MoveNext();
// Save its value (translated text)
 translation += string.Format(" {0}", Convert.ToString(translationLineString.Current));
}
// Remove first blank character
if (translation.Length > 1) { translation = translation.Substring(1); };
// Return translation
return translation;
}

I want to combine all these two code snippet and call TranslateText function in any html part like TranslateText(@Model.Description)

How can I do that?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,106 Reputation points Microsoft Vendor
    2021-08-28T06:02:41.707+00:00

    Hi @badcat ,

    I want to combine all these two code snippet and call TranslateText function in any html part like TranslateText(@默 .Description)

    You can create a service which contains the TranslateText method, then, injects the service in the view page and calling the TranslateText method.

    Please refer the following steps:

    Create a IViewTextFormat service with the following code (you can replace the TranslateText method to yours):

    public interface IViewTextFormat  
    {  
        string TranslateText(string input);  
    }  
      
    public class ViewTextFormat : IViewTextFormat  
    {  
        public string TranslateText(string input)  
        {  
            return input.ToUpper();  
        }  
    }  
    

    Register the IViewTextFormat service in the ConfigureServices method:

        public void ConfigureServices(IServiceCollection services)  
        {  
             services.AddScoped<IViewTextFormat, ViewTextFormat>();  
    

    Then, in the View page, injects the service:

    @model List<Core3_1MVC.Models.Student>  
      
    @using Core3_1MVC.Services  
    @inject IViewTextFormat TextFormat  
    @{  
        ViewData["Title"] = "Home Page";  
    }  
    <div class="text-center">  
        <h1 class="display-4"> @TextFormat.TranslateText("Welcome")</h1>  
        <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>  
    </div>  
      
    <table class="table table-hover">  
        <thead>  
            <tr><td>Name</td><td>EnrollmentDate</td></tr>  
        </thead>  
        <tbody>  
            @foreach (var item in Model)  
            {  
                <tr><td>@TextFormat.TranslateText(item.FirstMidName)</td><td>@item.EnrollmentDate</td></tr>  
            }  
        </tbody>  
    </table>  
    

    The result as below:

    127257-28.gif

    If you want to use the service in the controller method, you can also inject the service in the controller and call the TranslateText method, refer Dependency injection in ASP.NET Core.

    Besides, ASP.NET Core provides services and middleware for localizing into different languages and cultures. You can also try to use it: Globalization and localization in ASP.NET Core.


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments