简体   繁体   中英

Why is Culture Info different in controller and view in .NET Core MVC

I think .Net Core's community and documentation regarding Localization is poor. That's why I have some problem about it.

When I change 'Culture info' in Controller (see code below) is working well, but after that when I check 'culture info' in view is different. Please assist me to fix this issue.

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo('en-GB');

System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture; 

Why?

Because dotnet core it is more focused about async coding meaning Tasks are run per part. So controller action is 1 task. creating/executing the view is another task (or multiple tasks).

Tasks are run in different threads (by the TaskSchedular ) using a pool (re-using threads when task is finished). And thus there is no guarentee it is run in the same Thread.

How handle cultures?

Take a look at the documentation: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization . They provide perfect insight in how it works. (They tell you to use: CultureInfo.CurrentCulture but please read the documentation).

You may want to check this properties:

var cultureInfo = new System.Globalization.CultureInfo('en-GB');
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM