Ali.Ahmadi
Ali.Ahmadi

Reputation: 53

How to Change CurrentCulture in ASP.net Core 3.1

Multilingual App calls my APIs,i want to return messages,based on application language not based on app culture.So i decide to use Localization but Current Culture won't change with this code. Something like this :

[HttpPost("[action]/{languageid}")]
public async Task<IActionResult> login([FromBody] AccountViewModel model, [FromRoute] int languageid)
{
    var result = await signInManager.CheckPasswordSignInAsync(model.UserName, model.Password, true);
    CultureInfo cultureInfo;
    if(languageid == 1)
    {
        cultureInfo = new CultureInfo("fa-IR");
    }
    else
    {
        cultureInfo = new CultureInfo("en-US");

    }
    Thread.CurrentThread.CurrentCulture = cultureInfo;
    if (result)
        return Ok(new {Result = true , Message = _localize["Login-Success"] });

    return Ok(new { Result = false, Message = _localize["Login-failed"] });

}

is there any better solution for returning multilingual message based on app language? i don't want save this message in my database.

Upvotes: 1

Views: 2596

Answers (1)

Rosco
Rosco

Reputation: 2474

The Culture must be set for each request. Your login code does not save the setting anywhere so the setting is lost for the next webpage request.

ASP.NET Core has a framework for Localization which includes middleware to change the request culture.

See the documentation for changing request culture

In your case you could use the CookieRequestCultureProvider to set a cookie when the user logins in that has their preferred culture and UI culture.

e.g.

this.Response.Cookies.Append(
   CookieRequestCultureProvider.DefaultCookieName, 
   "c=fa-IR|uic=fa-IR");

Make sure to use CookieRequestCultureProvider.DefaultCookieName for the cookie name as this is the name the middleware will look for.

There are other ways to set the request culture like QueryStringRequestCultureProvider or a CustomProvider if needed.

Upvotes: 1

Related Questions