0

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?

koviroli
  • 1,422
  • 1
  • 15
  • 27
  • You setting Culture to `Current` thread, but after redirect your `Current` thread changes(does not have to, but you don't have control over it). What you need to do is to set culture for every request(write custom middleware, which reads cookie or any other source of information about culture and set's it for each request). It's better to reference ASP.NET guideline about it: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization?view=aspnetcore-2.2 – Uriil May 12 '19 at 17:08

1 Answers1

3

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;
Xueli Chen
  • 11,987
  • 3
  • 25
  • 36