Get the current culture in a controller asp.net-core

前端 未结 5 914
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 01:26

I have setup the cultures for my views and changing the culture in a controller but I can\'t seem to find how to know what culture I\'m currently using in a controller, I\'m loo

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-05 01:42

    ASP.Net Core 3.1:

    I can confirm that this is working if it's configured properly (see the second code block)

    CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
    

    In your startup class add this to the Configure method:

                IList supportedCultures = new List
                {
                    new CultureInfo("en-US"), //English US
                    new CultureInfo("ar-SY"), //Arabic SY
                };
                var localizationOptions = new RequestLocalizationOptions
                {
                    DefaultRequestCulture = new RequestCulture("en-US"), //English US will be the default culture (for new visitors)
                    SupportedCultures = supportedCultures,
                    SupportedUICultures = supportedCultures
                };
    
                app.UseRequestLocalization(localizationOptions);
    

    Then the user can change the culture by calling this action:

            [HttpPost]
            [ValidateAntiForgeryToken]
            public IActionResult SetCulture(string culture, string returnUrl)
            {
                HttpContext.Response.Cookies.Append(
                    CookieRequestCultureProvider.DefaultCookieName,
                    CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                    new CookieOptions { Path = Url.Content("~/") });
    
                if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                {
                    return LocalRedirect(returnUrl);
                }
    
                return RedirectToAction("Index", "Home");
            }
    

提交回复
热议问题