Reputation: 1339
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:
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
Upvotes: 2
Views: 824
Reputation: 941
Open up the resx file in design mode (just double click the file) and set the access modifier to public as the following -
I have found this following article a great help when working with localisation -
http://afana.me/archive/2011/01/14/aspnet-mvc-internationalization.aspx/
Upvotes: -1
Reputation: 18127
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()
};
});
Upvotes: 1