Asp.net-Core

ASP.NET Core DisplayAttribute 本地化

  • December 16, 2019

根據文件

執行時不會查找非驗證屬性的本地化字元串。在上面的程式碼中,“電子郵件”(來自

$$ Display(Name = “Email”) $$) 不會被本地化。

我正在尋找一種方法來本地化 DisplayAttribute 中的文本。有什麼建議可以以正確的方式進行嗎?

您可以設置ResourceTypeDisplayAttribute用於本地化文本的選項。

將資源.resx文件添加到您的項目中,例如MyResources.resx,並為您的欄位添加資源:

在此處輸入圖像描述

然後引用欄位的名稱和MyResources類型DisplayAttribute

[Display(Name = "RememberMe", ResourceType  = typeof(MyResources))]
public bool RememberMe { get; set; }

本地化的資源將被自動拉出(見文本框)

在此處輸入圖像描述

無論是視圖還是數據註釋,為所有本地化提供一個中心位置是我能想到的最佳方法,這也是我開始工作的方式。在安裝 nuget 包進行本地化後,在Startup.cs文件中添加以下程式碼

services.AddMvc().AddViewLocalization().AddDataAnnotationsLocalization(options => 
   options.DataAnnotationLocalizerProvider = (type, factory) => new StringLocalizer<Resources>(factory));

services.Configure<RequestLocalizationOptions>(options => {
  var cultures = new[]
  {
      new CultureInfo("en"),
      new CultureInfo("ar")
  };
  options.DefaultRequestCulture = new RequestCulture("en", "en");
  options.SupportedCultures = cultures;
  options.SupportedUICultures = cultures;
});

這樣DataAnnotationLocalizerProvider將來自Resources.{culture}.rex -(資源文件必須具有No code gen的訪問修飾符)-假設預設語言不需要資源,並且能夠訪問資源文件,因為不會生成程式碼並且必須創建具有相同名稱的空類。

並在**_ViewImports.cshtml**文件中註入以下內容

@inject IHtmlLocalizer<Resources> Localizer

通過這樣做,您現在有一個全域變數Localizer可在任何視圖中用於本地化目的。

這就是字元串本地化的中心位置

您可以在 ASP.NET Core中找到有關全球化和本地化的更多資訊

引用自:https://stackoverflow.com/questions/37833661