Reputation: 135
ASPNET.Core MVC 6 Localization – Sharedresources
Hi. I tried to create multilanguage web app in core 6 mvc with SharedResources resx files and it doesn’t work ☹ I have created empty dummy class SharedResource.cs in app root I have my SharedResource.resx in Resources folder
My Program.cs code is:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
builder.Services.AddControllersWithViews()
.AddViewLocalization
(LanguageViewLocationExpanderFormat.SubFolder)
.AddDataAnnotationsLocalization();
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")
));
var app = builder.Build();
var supportedCultures = new[] { "en-US", "cs", "sk" };
var localizationOptions = new RequestLocalizationOptions().SetDefaultCulture(supportedCultures[0])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
localizationOptions.ApplyCurrentCultureToResponseHeaders = true;
app.UseRequestLocalization(localizationOptions);
My Controller code is:
private readonly IStringLocalizer<SharedResource> sharedResourceLocalizer;
public HomeController(ApplicationDbContext db, IStringLocalizer<HomeController> postsControllerLocalizer, IStringLocalizer<SharedResource> sharedResourceLocalizer)
{
_db = db;
this.stringLocalizer = postsControllerLocalizer;
this.sharedResourceLocalizer = sharedResourceLocalizer;
}
public IActionResult Index(string? lang)
{
if (lang == null)
{
lang = "cz";
}
ViewData["Title"] = sharedResourceLocalizer["Onas"];
return View();
}
And I always get only resource key name in brackets (Onas)
Upvotes: 0
Views: 509
Reputation: 135
Finally, I found solution. It might be helpful for someone, so be careful about it.
Root Namespace issues When the root namespace of an assembly is different than the assembly name, localization doesn't work by default. To avoid this issue use RootNamespace, which is described in detail here
Warning
This can occur when a project's name is not a valid .NET identifier. For instance my-project-name.csproj will use the root namespace my_project_name and the assembly name my-project-name leading to this error.
Upvotes: 2