Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Core how to get application supported culture list

In my Startup.cs I added two cultures:

       var cultureLt = new CultureInfo("LT");
       var cultureEn = new CultureInfo("EN");
       var supportedCultures = new List<CultureInfo> {cultureEn, cultureLt};

       var requestLocalizationOptions = new RequestLocalizationOptions();
       requestLocalizationOptions.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider());
       requestLocalizationOptions.SupportedCultures = supportedCultures;
       requestLocalizationOptions.SupportedUICultures = supportedCultures;

       app.UseRequestLocalization(requestLocalizationOptions);

I need to get this list in constructor and now in consturctor controller I initialized variable

private readonly IOptions<RequestLocalizationOptions> _locOptions;

and in Action I'm trying to get this list like this:

var cultureItems = _locOptions.Value.SupportedUICultures
            .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
            .ToList();

but the problem is that this line only returns the culture that is currently set in application... How to get both EN and LT cultures?

like image 855
Nikas Žalias Avatar asked Dec 07 '16 12:12

Nikas Žalias


1 Answers

You must configure the RequestLocalizationOptions.

public void ConfigureServices(IServiceCollection services)
{         
     // ... enter code here

     // RequestLocalizationOptions must to be configured 
     var cultureLt = new CultureInfo("LT");
     var cultureEn = new CultureInfo("EN");
     var supportedCultures = new[] { cultureEn, cultureLt };

     services.Configure<RequestLocalizationOptions>(options =>
     {
         options.SupportedCultures = supportedCultures;
         options.SupportedUICultures = supportedCultures;
     });

     // Add them to IServiceCollection
     services.AddLocalization();

     // ... enter code here
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // ... enter code here

    // add RequestLocalizationMiddleware to pipeline
    app.UseRequestLocalization();

    app.UseMvc...
}
like image 168
tmg Avatar answered Oct 20 '22 00:10

tmg