ASP.Net Core Localization
See github source, sample
TODO: based on pre-release RC2, to be updated to RTM
Nuget packages
- "Microsoft.Extensions.Localization"
- "Microsoft.AspNetCore.Localization"
RequestLocalizationOptions
RequestLocalizationOptions are configured in Startup.
There are 3 built-in providers to set the culture of a request: QueryStringRequestCultureProvider, CookieRequest ("ASPNET_CULTURE" cookie) and AcceptLanguageHeader
You can set the cookie in an action method
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}
Startup
- Startup.ConfigureServices: services.AddLocalization(options => options.ResourcesPath = "ResourcesFolder")
The ResourcesPath is the folder containing the .resx files.
services.AddMvc() // Add support for finding localized views, based on file name suffix, e.g. Index.fr.cshtml .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) // Add support for localizing strings in data annotations (e.g. validation messages) .AddDataAnnotationsLocalization(); - Startup.Configure:
app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-US"), SupportedCultures = new List<CultureInfo> { new CultureInfo("en-US"), new CultureInfo("en-GB") } });
In controllers, the ctor asks for IHtmlLocalizer<resourceName>.
public class AboutController : Controller
{
private IHtmlLocalizer<AmazingResource> _htmlLocalizer;
public AboutController(IHtmlLocalizer<AmazingResource> localizer)
{
_htmlLocalizer = localizer;
}
[HttpGet]
public string Get()
{
return _htmlLocalizer["Name"];
}
}
Access localization via features
var requestCultureFeature = context.Features.Get<IRequestCultureFeature>(); var requestCulture = requestCultureFeature.RequestCulture;
Views
The one nice use-case for dependency injection into views, and there's a tag-helper (the string is the key).
@inject IViewLocalizer Localizer
@{
ViewData["Title"] = Localizer["Home Page"];
}
<p>@Localizer("Will be localized") </p>
<p asp-loc>This will be localized</p>