Search code examples
c#asp.net-coreasp.net-core-mvc

How to use localization in asp.net?


I'm trying to figure out how to use the localization in ASP.NET, I actually followed the Microsoft Documentation but I'm pretty confused right now.

This is what I did so far:

Inside the Configure method I added the following code (at the top of all):

var supportedCultures = new[]
{
   new CultureInfo("it-IT"),
   new CultureInfo("en-EN")
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
   DefaultRequestCulture = new RequestCulture("it"),
   SupportedCultures = supportedCultures,
   SupportedUICultures = supportedCultures
});

so essentially I declared two supported languages, and set the italian to default.

Then inside the ConfigureServices I specified the ResourcesPath:

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

This is actually the folder content:

enter image description here

I setted for both .resx file the access modificator to public, and then inside the _ViewImports.cshtml I added this:

@using Microsoft.AspNetCore.Mvc.Localization

The problem is that when I type @Resources inside a View I get:

'Resources' is not accessible due to the level of security


Solution

  • If you want to access the localization strings for controller in the view, you could do it that way:

    @inject IStringLocalizer<HomeController> localazier
    

    After that @localazier["YourKey"]

    I advise you to create empty class in your project for an example SharedResources and create specific resx file for it and after that just use it everywhere with @inject IStringLocalizer<SharedResources> localazier

    Additionally a possible problem is your default culture. Asp.net core looks for the culture into one of this 3 places:

    QueryStringRequestCultureProvider
    CookieRequestCultureProvider
    AcceptLanguageHeaderRequestCultureProvider
    

    and only if the culture is empty for any of them it will take your default culture. So you should turn off AcceptLanguageHeaderRequestCultureProvider as possibility, because a lot of user could have defined it in their browser and it is possible to be different from IT.

    This is the way to take it only from query string or cookie, so I advise you to implement it that way.

    services.Configure<RequestLocalizationOptions>(options =>
    {
        options.RequestCultureProviders = new List<IRequestCultureProvider>()
        {
            new QueryStringRequestCultureProvider(),
            new CookieRequestCultureProvider()
        };
    });