How to set up languages in Asp.net Core

Asked

Viewed 696 times

5

I’m setting up the AddLocalization
So the problem is that Resources are in a separate class library of the project and I don’t know how to set up.

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

inserir a descrição da imagem aqui

  • 1

    With full namespace does not solve? Ex.: "adopts me.shared.Languages"?

1 answer

1


To configure the languages in Asp.net core I used the following configuration:

In the Startup file

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

   services.AddMvc()
    .AddViewLocalization(

     LanguageViewLocationExpanderFormat.SubFolder,
     opts => {
      opts.ResourcesPath = "Resources";
     })
    .AddDataAnnotationsLocalization()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  }

I put the translation files here as shown in the image

inserir a descrição da imagem aqui

To access the translation in the controller I used

private readonly IStringLocalizer<HomeController> _localizer;



public HomeController(IStringLocalizer<HomeController> localizer)
{   
    _localizer = localizer;
 }

Then to access a specific text I used

 ViewData["Contact"] = _localizer.GetString("Contact").Value;

Step into the ViewData["Contact"] the field with the name Contact which are in the files:

  1. Controllers.HomeController.en.resx
  2. Controllers.HomeController.en-PT.resx

These files in your order:

  1. Views.Shared. _Layout.en-PT.resx
  2. Views.Shared. _Layout.en.resx

Affect the file _Layout.cshtml

Within the _Layout.cshtml file we can translate into that file without existing controller we use Razor

@inject IViewLocalizer Localizer

And to put a translation variable we use for example:

@Localizer["MenuHome"]

"Menuhome" is the name of the variable declared in the file Views.Shared. _Layout.en.resx and Views.Shared. _Layout.en-PT.resx

Then to see the pages in the different languages just access the link of your site: https://linkdosite/Controller/Nomination? Culture=en
To show the translation in this case in English

Browser other questions tagged

You are not signed in. Login or sign up in order to post.