Closed Vinko90 closed 3 years ago
Please try the following step.
At first, rewrite your "Startup.cs" like this.
Before:
/* Startup.cs */
public void ConfigureServices(IServiceCollection services)
{
....
services.AddI18nText();
....
After:
/* Startup.cs */
public void ConfigureServices(IServiceCollection services)
{
....
services.AddI18nText(options =>
{
// 👇 Stop persisting current language by I18n text library's mechanism
// because the current language is persisted in cookie now.
options.PersistanceLevel = PersistanceLevel.None;
// 👇 The language at the session starting is now provided by cookie
// inside the HTTP request, and it applies to "CultureInfo.CurrentUICulture"
// by the "RequestLocalization" middleware.
// So you have to override the detecting initial language function of
// the I18n text library for returning the value of "CultureInfo.CurrentUICulture" to it.
options.GetInitialLanguageAsync = (_, _) => ValueTask.FromResult(CultureInfo.CurrentUICulture.Name);
});
....
And finally, please comment out some code that is no longer needed in your "MayLayout" component.
/* MainLayout.razor.cs */
...
public partial class MainLayout
{
...
// 👇 You don't have to access the I18n text service instance to get or set
// the current language anymore.
// Just do it that get the current language via "CultureInfo",
// set the language user changes to cookies.
//protected override async Task OnInitializedAsync()
//{
// base.OnInitialized();
// string lang = await I18nText.GetCurrentLanguageAsync();
// SetLanguageAsync(lang);
//}
private async Task RequestCultureChangeAsync(string value)
{
...
}
//private async Task SetLanguageAsync(string value)
//{
// await I18nText.SetCurrentLanguageAsync(value);
//}
My Sample project: 📂 BlazorApp1.zip
Thank you so much for providing explanation and example code, everything works as expected :)
I am trying to use cookie in Blazor.Server .NET5 in order to remember the language setting of each user however I can't manage to make it work. For some reason when I start the page I can see that the main layout refresh twice, the first time I see the language from cookie (meaning last stored value) and then the second time the default language. Can someone please help me out?
Startup
Culture Controller
MainLayout.razor.cs