Detailed explanation of multilingual support in asp.net core

Time:2021-5-4

First, add localization, add view localization, and configure request localization options in configuration services of startup


public void ConfigureServices(IServiceCollection services)
{
  services.AddLocalization(options => options.ResourcesPath = "Resources");

  services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

  services.Configure<RequestLocalizationOptions>(
    opts =>
    {
      var supportedCultures = new List<CultureInfo>
      {
        new CultureInfo("en-US"),
        new CultureInfo("zh-CN")
      };
      opts.SupportedCultures = supportedCultures;
      opts.SupportedUICultures = supportedCultures;
    });
}

Apply requestlocalizationoptions in the configure() method of startup


var requestLocalizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
app.UseRequestLocalization(requestLocalizationOptions);

And then in the_ In the layout.cshtml view, the suffix of the page title is displayed in multi language through iviewlocalizer interface


@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
<!DOCTYPE html>
<html>
<head>
  <title>@ViewData["Title"] - @Localizer["SiteTitle"]</title>
</head>
<body>
</body>
</html>

Then create the Resources folder in the asp.net core web project, and add views.shared.asp_ Layout.en-us.resx and views.shared_ Layout.zh-cn.resx file, views.shared_ Layout.resx file, and add the sentence text corresponding to “sitetitle”:

1)Views.Shared._Layout.en-Us.resx

2)Views.Shared._Layout.zh-CN.resx

When running asp.net core site, the text of the corresponding language will be displayed according to the browser’s language settings (accept language header), or culture query parameters, or. Aspnetcore.culture cookie value

Note: do not add views. Shared_ Layout.en-us.resx, otherwise it will be encountered when adding. Resx file with code language name   ” Custom tool resxfilecodegenerator failed to produce an output for input file… But did not log a specific error.

Be sure to see the following reference documents:Globalization and localization 

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.