static void

ASP.Net Core Localization

See github source, sample

TODO: based on pre-release RC2, to be updated to RTM

Nuget packages

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

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>