How to set up languages in Asp.net Core

6

I'm setting up AddLocalization    So the problem is that Resources is in a separate class library of the project and I do not know how to configure it.

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

    
asked by anonymous 01.09.2018 / 23:42

1 answer

2

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

ForthecontrollertoaccessthetranslationIused

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

ThentoaccessaspecifictextIused

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

Step to the% with the Contact field found in the files:

  • Controllers.HomeController.en.resx
  • Controllers.HomeController.pt-PT.resx
  • This file in your order:

  • Views.Shared._Layout.pt-PT.resx
  • Views.Shared._Layout.en.resx
  • Affect the _Layout.cshtml

    Inside the _Layout.cshtml file we can translate within this file without driver we use razor

    @inject IViewLocalizer Localizer
    

    And to put a translation variable we use for example:

    @Localizer["MenuHome"]
    

    where "MenuHome" is the name of the variable declared in the file Views.Shared._Layout.en.resx and Views.Shared._Layout.pt-PT.resx >

    Then to see the pages in different languages just access the link of your site: link To show the translation in this case in English

        
    05.01.2019 / 01:41