2016-12-06 84 views
1

我有一個asp.net核心項目,我想將默認語言設置爲nl-BE。由於某種原因,它總是採取語言en-US始終是相同的文化:en-US

請參閱下面的代碼(ps:我創建了我自己的ApplicationLocalizer誰從數據庫中獲取資源=>正常工作)。

Startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
      //Add MVC 
      services.AddMvc() 
       .AddViewLocalization(); 

      //Localization factory 
      services.AddSingleton<IStringLocalizerFactory, ApplicationLocalizerFactory>(); 

      ... 
} 


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context) 
{ 
      ... 

      //Localization 
      var supportedCultures = new[] 
       { 
        new CultureInfo("en-US"), 
        new CultureInfo("nl-BE") 
       }; 
      var options = new RequestLocalizationOptions { 
       DefaultRequestCulture = new RequestCulture("nl-BE"), 
       SupportedCultures = supportedCultures, 
       SupportedUICultures = supportedCultures 
      }; 
      app.UseRequestLocalization(options); 

      ... 
} 

控制器

public string Index() 
{ 
    return CultureInfo.CurrentCulture.Name; 
} 

的這段代碼總是返回的en-US

有人可以幫我解決這個問題?

+0

您的代碼看起來不錯,我懷疑即使默認文化不是en-US,您的Web瀏覽器語言首選項設置爲en-US,因此它會使用它,因爲它受支持。請確保您沒有設置en-US語言的cookie。我曾經有一個本地主機cookie,就像玩本地化示例一樣,所以清除cookie可能有助於 –

+0

Thxs的回覆。我已經將瀏覽器語言更改爲nl-BE並刪除了所有的cookies,但它一直在使用en-US語言 – Wouter

回答

1

後搜索沒有結果的解決方案的時間,我去了沉重的調試和意識到,作爲配置聲明的中間件服務是在爲了執行(IApplicationBuilder應用...)。因此,在控制器操作執行後,本地化中間件被調用

當我移動app.UseRequestLocalization(選項),在開始的時候我得到了正確本地化主題/ CultureInfo的在控制器動作調用。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, 
     IApplicationLifetime appLifetime) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     // THIS HAS TO BE A VERY FIRST MIDDLEWARE REGISTRATION 
     SetUpLocalization(app); 

     app.UseCors("AllowAllOrigins"); 

     app.UseMvc(); 

     appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose()); 
    } 

    private static void SetUpLocalization(IApplicationBuilder app) 
    { 
     var supportedCultures = new[] 
     { 
      new CultureInfo("en-US"), 
      new CultureInfo("pl-PL"), 
      new CultureInfo("pl") 
     }; 

     var options = new RequestLocalizationOptions 
     { 
      DefaultRequestCulture = new RequestCulture("en-US", "en-US"), 
      SupportedCultures = supportedCultures, 
      SupportedUICultures = supportedCultures 
     }; 
     // Configure the Localization middleware 
     app.UseRequestLocalization(options); 
    } 
相關問題