Reputation: 1864
I have a _Layout.cshtml
in my MVC project, where I want to set the page <title>
via ASP.NET Core localization.
This is a (simplified) repro:
@inject IHtmlLocalizer<SharedResources> SharedLocalizer;
<!DOCTYPE html>
<html>
<head>
<title>@SharedLocalizer["My Default Language Text"]</title>
</head>
<body>
@SharedLocalizer["My Default Language Text"]
@RenderBody()
</body>
</html>
The resource in body
is being localized correctly and renders the text from the resource file as expected. But the resource in head
is not and stays "My Default Language Text" no matter what I try.
Please note that I see this behaviour in both cases:
@inject IHtmlLocalizer<SharedResources> SharedLocalizer
(like in the code above)IViewLocalizer
via @inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer Localizer
I'm running v1.1.3
of the Microsoft.AspNetCore.*
packages.
Upvotes: 1
Views: 1252
Reputation: 40
I had this problem using IStringLocalizer on .net core 5. In my case, the problem happened because of the following:
As I was using the LanguageViewLocationExpanderFormat.Suffix configuration on my Startup.cs :
services.AddLocalization(o => { o.ResourcesPath = "Resources"; });
services.AddControllersWithViews()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
And my Resources folder were like:
Resources >
Because of that above configuration, my _layout.cshtml doesn't got any of the resourses injected.
To fix the problem, we have two options:
1st Option:
Create specific resx file(s) for your _layout.cstml such as "Views.Shared._Layout.en-US.resx", and inject your layout view with:
@using Microsoft.AspNetCore.Mvc.Localization;
@inject IViewLocalizer Localizer
2nd Option:
Create generic resx file(s) for your application/context, such as "Controllers.HomeController.en-US.resx" in your "Resources" folder, and inject both (or more) views specifying the controller with:
@using Microsoft.AspNetCore.Mvc.Localization;
@using Yourproject.Controllers;
@inject Microsoft.Extensions.Localization.IStringLocalizer<HomeController> Localizer
Upvotes: 0
Reputation: 1864
I just found that my problem was related to this bug: https://github.com/aspnet/Localization/issues/277 (non-english localization as the default localization).
Upvotes: 3