0

I am trying to implement localization in our application, but I just cannot get it to work. My problem is how can I set the culture properly and how can access the localization string as per the culture set.

I am trying to set the culture from dropdownlist which is at the login page and pulling the resources from database.

Startup file

public void ConfigureServices(IServiceCollection services)
    {

        services.AddSqlLocalization(options => options.UseTypeFullNames = true);

        services.AddMvc(o =>
        {
            o.Filters.Add(new LanguageActionFilter());
        })
        .AddViewLocalization()
        .AddDataAnnotationsLocalization()
        .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());


        services.Configure<RequestLocalizationOptions>(
             options =>
             {
                 var supportedCultures = new List<CultureInfo>
                     {
                         new CultureInfo("de-DE"),
                        new CultureInfo("en-US"),
                        new CultureInfo("de-DE"),
                       new CultureInfo("fr-FR"),

                     };

                 options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                 options.SupportedCultures = supportedCultures;
                 options.SupportedUICultures = supportedCultures;
             });

    }

Controller code:- Calling from dropdown index changed through ajax.

[HttpPost]
    public IActionResult SetLanguage(string culture)
    {

            AppTenant tenant = HttpContext.Session.GetObjectFromJson<AppTenant>("TenantInfo");

            if (tenant != null)
            {
                tenant.LoggedInCulture = strdata[0];
                HttpContext.Session.SetObjectAsJson("TenantInfo", tenant);

                string cookieFormat = "culture-name";
                string cookieVal = cookieFormat.Replace("culture-name", tenant.LoggedInCulture);

                Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(cookieVal)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddMonths(3) }
               );
            }


        List<SelectListItem> items = new List<SelectListItem>();
        items = HttpContext.Session.GetObjectFromJson<List<SelectListItem>>("LanguageData");

        foreach (var item in items)
        {
            if (item.Value == culture)
            {
                item.Selected = true;
            }
            else
            {
                item.Selected = false;
            }
        }
        var viewModel = new LMS_User { ReturnUrl = string.Empty, LanguageList = items };

        return View("Login", viewModel);

    }

Resource Filter:- Here I have tried to set the culture in OnResourceExecuting and OnResourceExecuted method like follow.

public void OnResourceExecuted(ResourceExecutingContext context)
    {
       AppTenant tenant = context.HttpContext.Session.GetObjectFromJson<AppTenant>("TenantInfo");

        CultureInfo.CurrentCulture = new CultureInfo(_culture);
        CultureInfo.CurrentUICulture = new CultureInfo(_culture);
    }

In Resource filter where should we set the culture as I am not getting the current dropdown value in OnResourceExecuting but getting in OnResourceExecuted through session.

My SqlStringLocalizerFactory class where pulling resource from database

public class SqlStringLocalizerFactory : IStringLocalizerFactory, IStringExtendedLocalizerFactory
{
public IStringLocalizer Create(Type resourceSource)
    {

        SqlStringLocalizer sqlStringLocalizer;

        _culture = CultureInfo.CurrentCulture.ToString();
}

Here I want to get the selected culture, which is I am not getting it, it is coming as 'en-US'

Any help on this appreciated !

1 Answer 1

1

You have to change current thread Culture and UICulture properties to required culture. Add following code to your SetLanguage action and that should solve your issue:

CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(culture);
Thread.CurrentThread.CurrentCulture = new  System.Globalization.CultureInfo(cultureInfo ); 
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cultureInfo ); 
Sign up to request clarification or add additional context in comments.

1 Comment

@Rohit This is how I has been dealing with localization task, when I had to switch languages for the app I've been working on. So I know for the fact, that this way job would be done. I think you need to make sure, that UICulture on a thread has been actually changed. It looks like it had not been.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.