0

我很努力讓我的應用程序正確地本地化字符串。感覺我搜索了網絡的每一個角落,卻沒有找到我期望的東西。本地化ASP.NET Core MVC應用程序

我使用RouteDataRequestCultureProvider和第一個問題我想解決的是能夠使用的文化,例如「短手版」在創建時培養的sv代替sv-SEsv被視爲sv-SE。這不會自動發生。

二是剛開該應用顯示一個本地化的字符串。下面是我如何配置本地化

public static IServiceCollection ConfigureLocalization(this IServiceCollection services) 
{ 
    services.AddLocalization(options => 
    { 
     options.ResourcesPath = "Resources"; 
    }); 
    services.Configure<RequestLocalizationOptions>(options => 
    { 
     var supportedCultures = new[] 
      { 
      new System.Globalization.CultureInfo("sv-SE"), 
      new System.Globalization.CultureInfo("en-US")       
      };     
     options.DefaultRequestCulture = new RequestCulture(culture: "sv-SE", uiCulture: "sv-SE"); 
     options.SupportedCultures = supportedCultures; 
     options.SupportedUICultures = supportedCultures;     
     options.RequestCultureProviders = new[] 
     { 
      new RouteDataRequestCultureProvider 
      { 
       Options = options 
      } 
     }; 
    }); 
    return services; 
} 

然後在Configure我做app.UseRequestLocalizationOptions();其注入先前配置的選項。

在文件夾Resources我創建了資源文件Resource.resxResource.sv.resx

在我的視圖文件中,我試過注入IStringLocalizer(因爲沒有默認實現註冊失敗)和IStringLocalizer<My.Namespace.Resources.Resource>,但沒有任何選項可用。我也試着到舊的方式方法@My.Namespace.Resources.Resource.StringToLocalize

它是不可能有一個共享的資源文件?不想訴諸於Resource\Views\ViewA.resxResource\Controllers\AController.resx

謝謝

+0

類是不可能有一個共享的資源文件?我認爲這是正確的。 就我個人而言,我認爲在dotnet核心的默認本地化是混亂的。 http://www.dotnetcurry.com/aspnet/1314/aspnet-core-globalization-localization http://scottkdavis.com/posts/localizing-an-asp-web-application.html –

回答

0

所以我得到了這個工作。在我的Resource文件夾我有我Lang.resx -files與public訪問修飾符

我發現this,並添加了類Lang(命名爲文件LangDummy不與資源文件衝突)屬於該項目的根命名空間

然後在我看來,進口文件@inject Microsoft.Extensions.Localization.IStringLocalizer<My.Namespace.Lang> StringLocalizer,並用它@StringLocalizer["PropertyInResxFile"]。理想情況下,我想使用生成的靜態屬性來實現類型安全,並且更容易重構,並且在任何地方都可以使用,只是感覺到臃腫。

這適用於通過數據註解本地化屬性以及這裏我用ResourceType = typeof(My.Namespace.Resources.Lang),即對於RESX文件