Reputation: 295
Have added new .Resx file into Resources folder under .Net Core Web 3 project.
When try to access resx file its not available on controller or validation attribute.
What is the right way to work with Resx files in .Net Core.
Upvotes: 3
Views: 3993
Reputation: 12715
For Configuring Localization in Controller, you could refer to the following steps
1.Configure Localization in the Startup.ConfigureServices
method and set cultures in the Startup.Configure
method. The localization middleware must be configured before any middleware which might check the request culture :
public void ConfigureServices(IServiceCollection services)
{
//Adds the localization services to the services container. The code above also sets the resources path to "Resources"
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddControllersWithViews()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("fr"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
2.The ConfigureServices
method sets the ResourcesPath
to "Resources", so the project relative path for the home controller's French resource file is Resources/Controllers.HomeController.fr.resx
. Alternatively, you can use folders to organize resource files. For the home controller, the path would be Resources/Controllers/HomeController.fr.resx
.
Then use IStringLocalizer
which uses the ResourceManager and ResourceReader to provide culture-specific resources at run time to access Resx files in Controller .
public class HomeController : Controller
{
private readonly IStringLocalizer<HomeController> _localizer;
public HomeController(IStringLocalizer<HomeController> localizer)
{
_localizer = localizer;
}
public IActionResult About()
{
ViewData["Message"] = _localizer["Your application description page."];
return View();
}
}
For more details , you could refer to the official doc which contains the sample code and DataAnnotations localization.
Upvotes: 1