koviroli
koviroli

Reputation: 1453

ASP.NET Core MVC, set thread culture does not have effect

I dealing with multilanguage site.

I have a partial view where my approach is to set specific language to my website.

<form asp-controller="Language" asp-action="SetLanguage" method="post" class="form-horizontal">
    <label>Language:</label>
    <select name="culture">
        <option value="hu">Magyar</option>
        <option value="eng">English</option>
    </select>
    <button type="submit" class="btn btn-link navbar-btn navbar-link">Change</button>
</form>

While I debugging I can check that the culture have been set right, but when my RedirectToPage(...) called, then I debug again and my CurrentThread.CurrentCulture get to the same as it was.

public IActionResult SetLanguage(string culture)
{
    string cookieCultureValue = culture;
    Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cookieCultureValue)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
    );

    Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);

    return RedirectToPage("/Index");
}

How could I solve this problem? Do I do this multilanguage thing right?

Upvotes: 0

Views: 2476

Answers (1)

Xueli Chen
Xueli Chen

Reputation: 12715

ASP.Net Core, it is more focused about async coding meaning Tasks are run per part. So controller action is 1 task. RedirectToPage 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.

You could try CultureInfo.DefaultThreadCurrentCulture Property in your SetLanguage method like below :

CultureInfo newCulture = new CultureInfo(culture);

CultureInfo.DefaultThreadCurrentCulture = newCulture;
CultureInfo.DefaultThreadCurrentUICulture = newCulture;

Then get the CurrentThread.CurrentCulture in Index

var currentCulture = Thread.CurrentThread.CurrentCulture;

Upvotes: 3

Related Questions