Change culture for an ASP.NET Core 2 Razor page

Viewed 6475

I created an ASP.NET Core 2 projects with razor pages and I would like to give the opportunity to the visitor to select a language. The first problem that I had was to change the web application url so that ti will include the current language code. I solved this problem by adding the following code in ConfigureServices.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Account/Manage");
                options.Conventions.AuthorizePage("/Account/Logout");
                options.Conventions.AddFolderRouteModelConvention("/", model =>
                {
                    foreach (var selector in model.Selectors)
                    {
                        var attributeRouteModel = selector.AttributeRouteModel;
                        attributeRouteModel.Template = AttributeRouteModel.CombineTemplates("{language=el-GR}", attributeRouteModel.Template);
                    }
                });
            });
    }
}

Now I could visit a page using the following URL:

http://domain/el-GR/MyPage

The last thing that I would like to do is to change the culture of each request. The best solution that I fount which I do not like is to put the following code in my page:

System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo((string)RouteData.Values["language"]);
System.Globalization.CultureInfo.CurrentUICulture = new System.Globalization.CultureInfo((string)RouteData.Values["language"]);

This is not nice because I will have to add these lies in every razor page that I will create in my project.

Is there another way to set the culture for all the requests of my web application?

1 Answers

Refer to this article: https://joonasw.net/view/aspnet-core-localization-deep-dive

There are a few methods, I use the RequestCultureProviders.

NuGet: Microsoft.AspNetCore.Localization

in my Startup.Configure method.

IList<CultureInfo> sc = new List<CultureInfo>();
sc.Add(new CultureInfo("en-US"));
sc.Add(new CultureInfo("zh-TW"));

var lo = new RequestLocalizationOptions
{
   DefaultRequestCulture = new RequestCulture("en-US"),
   SupportedCultures = sc,
   SupportedUICultures = sc
};
var cp = lo.RequestCultureProviders.OfType<CookieRequestCultureProvider>().First();
cp.CookieName = "UserCulture"; // Or whatever name that you like

app.UseRequestLocalization(lo);

Set your cookie "UserCulture" to "c=zh-TW|uic=zh-TW" once.

And it works magically.

Related