Multi languages in ASP.NET MVC core

In this video, I'm going to show how to add another language to your website. Actually, in this post, I will use a resource file for each language, in fact, it does not have necessary to add a resource file for each language.

  1. Create a new project
  2. Add a folder called Resources
  3. Add 3 resources file: (SharedResource.de-DE.resx , SharedResource.en-US.resx , SharedResource.nl-NL.resx )

In each file add your variables with appropriate meaning:

For example, in Germany language:

And for English:

Finally, for Netherland:

  1. Create a .cs file called ShareResource.cs and LanguageService.cs in you costume path:

For ShareResource.cs we have below code:

public class ShareResource
    {

    }

 For LanguageService.cs we have below code:

public class LanguageService
    {
       private readonly IStringLocalizer _localizer;

        public LanguageService(IStringLocalizerFactory factory)
        {
            var type = typeof(ShareResource);
            var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
            _localizer = factory.Create("SharedResource", assemblyName.Name);
        }

        public LocalizedString Getkey(string key)
        {
            return _localizer[key];
        }

    }

Note: Do not forget to add the usings

  1. In startup file in ConfigureServices function add below codes:
services.AddSingleton<LanguageService>();

            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddMvc()
                .AddViewLocalization()
                .AddDataAnnotationsLocalization(options =>
                {
                    options.DataAnnotationLocalizerProvider = (type, factory) =>
                    {

                        var assemblyName = new AssemblyName(typeof(ShareResource).GetTypeInfo().Assembly.FullName);

                        return factory.Create("ShareResource", assemblyName.Name);

                    };

                });



            services.Configure<RequestLocalizationOptions>(
                options =>
                {
                    var supportedCultures = new List<CultureInfo>
                        {
                            new CultureInfo("en-US"),
                            new CultureInfo("nl-NL"),
                            new CultureInfo("de-DE"),
                        };



                    options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");

                    options.SupportedCultures = supportedCultures;
                    options.SupportedUICultures = supportedCultures;
                    options.RequestCultureProviders.Insert(0, new QueryStringRequestCultureProvider());

                });

 

Also, in Configure function add below codes:

  var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();

            app.UseRequestLocalization(locOptions.Value);
  1. Open HomeController and add an IActionResult:
  public IActionResult ChangeLanguage(string culture)
        {
            Response.Cookies.Append(CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                new CookieOptions() { Expires = DateTimeOffset.UtcNow.AddYears(1) });

            return Redirect(Request.Headers["Referer"].ToString());
        }
  1. In _Layout.cshtml create a dropdown for 3 languages with your favorite design:

<div class="nav-wrapper">
                    <div class="sl-nav">
                        Sprache:
                        <ul>
                            <li>
                               <b>Deutsch</b> <i class="fa fa-angle-down" aria-hidden="true"></i>
                                <div class="triangle"></div>
                                <ul class="language">

                                    <li><a asp-controller="Home" asp-action="ChangeLanguage" asp-route-culture="en-US" class="nav-link"><i class="flag-icon flag-icon-gb"></i> English</a></li>

                                    <li><a asp-controller="Home" asp-action="ChangeLanguage" asp-route-culture="de-DE" class="nav-link"><i class="flag-icon flag-icon-de"></i> Deutsch</a></li>

                                    <li><a asp-controller="Home" asp-action="ChangeLanguage" asp-route-culture="nl-NL" class="nav-link"><i class="flag-icon flag-icon-nl"></i> Netherland</a></li>

                                </ul>

                            </li>

                        </ul>

                    </div>

                </div>

 

  1. And inject the language service that you made it before:
@inject LanguageService language
  1. Finally, for each word that you want be change add the language variable. For example, in Index.cshtml:
@{

    ViewData["Title"] = "Home Page";

}

@inject LanguageService language



<div class="text-center">

    <h1 class="display-4">@language.Getkey("welcome")</h1>

</div>

 

Run your project and click on languages, the words should be changed:

 

 

Recent Comments