【问题标题】:ASP.NET MVC Core how to get application supported culture listASP.NET MVC Core 如何获取应用程序支持的文化列表
【发布时间】:2016-12-07 21:37:41
【问题描述】:

在我的 Startup.cs 中,我添加了两种文化:

       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);

我需要在构造函数中获取这个列表,现在在构造函数控制器中我初始化了变量

private readonly IOptions<RequestLocalizationOptions> _locOptions;

在行动中,我试图获得这样的列表:

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

但问题是这一行只返回当前在应用程序中设置的文化...如何同时获得 EN 和 LT 文化?

【问题讨论】:

    标签: c# asp.net asp.net-mvc localization


    【解决方案1】:

    您必须配置 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...
    }
    

    【讨论】:

    • 它不能解决问题(asp.net core 3),无论如何我创建本地化选项的方式(AddSupportedCultures,options.SupportedCultures),列表只包含当前文化
    • .net 5. 已解决。将配置从 Configure 移动到 ConfigureServices,它就像一个魅力。
    • @wondertalik 这在 .net 5(与 core 3.1 相比)有什么不同?
    • @HappyNomad,在这种情况下是一样的。但是有很多小的变化。您可以在official site 上阅读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    相关资源
    最近更新 更多