溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ASP.NET Core如何實現(xiàn)從文本文件讀取本地化字符串

發(fā)布時間:2021-06-28 14:50:59 來源:億速云 閱讀:172 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)ASP.NET Core如何實現(xiàn)從文本文件讀取本地化字符串的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

實施全球化和本地化

國際化涉及全球化和本地化。 全球化是設(shè)計支持不同區(qū)域性的應(yīng)用程序的過程。 全球化添加了對一組有關(guān)特定地理區(qū)域的已定義語言腳本的輸入、顯示和輸出支持。

本地化是將已經(jīng)針對可本地化性進(jìn)行處理的全球化應(yīng)用調(diào)整為特定的區(qū)域性/區(qū)域設(shè)置的過程。 有關(guān)詳細(xì)信息,請參閱本文檔鄰近末尾的全球化和本地化術(shù)語。

應(yīng)用本地化涉及以下內(nèi)容:

  • 使應(yīng)用內(nèi)容可本地化

  • 為支持的語言和區(qū)域性提供本地化資源

  • 實施策略,為每個請求選擇語言/區(qū)域性

全球化和本地化主要在兩個位置實施,一是控制器,二是視圖。在視圖里實施全球化和本地化,要在Startup.ConfigureServices()里添加

services.AddMvc().AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix,
  opt => { opt.ResourcesPath = "Resources"; })

services.Configure(
 opts =>
 {
 var supportedCultures = new HashSet<CultureInfo>
 {
 CultureInfo.CurrentCulture,
 CultureInfo.CurrentUICulture,
 new CultureInfo("zh"),
 new CultureInfo("en"),
 };

 // Formatting numbers, dates, etc.
 opts.SupportedCultures = supportedCultures.ToList();
 //// UI strings that we have localized.
 opts.SupportedUICultures = supportedCultures.ToList();
 });

其中AddViewLocalization()定義在Microsoft.AspNetCore.Localization命名空間。opt.ResourcesPath = "Resources"表示在Resources文件夾尋找本地化資源文件。第二段代碼設(shè)置本應(yīng)用程序支持的語言,似乎沒有簡單辦法說支持任何語言。

還需要在Startup.Configure()啟動請求本地化中間件。默認(rèn)設(shè)置會從URL、Cookie、HTTP Accept-Language標(biāo)頭讀取目標(biāo)語言。

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
 var options = app.ApplicationServices.GetService>();
 app.UseRequestLocalization(options.Value);

 app.UseMvc();
}

接著,在視圖cshtml文件里添加

@inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer Lo
<fieldset>
 <legend>@Lo["Show following columns"]</legend>
 <div id="visibleColumnsForTable" class="loading-prompt" data-time="10"></div>
</fieldset>

現(xiàn)在先不添加資源文件,直接運(yùn)行程序測試一下,程序會輸出Show following columns。這表明,如果ASP.NET Core找不到資源文件,會輸出鍵名。因此,微軟建議在ASP.NET Core,直接用自然語言作為鍵名。

然后添加資源文件。ASP.NET Core支持兩種資源文件組織方案。因為我們在AddViewLocalization時選擇了LanguageViewLocationExpanderFormat.Suffix,假設(shè)要對View\Home\Index.cshtml提供大陸簡體文本,要么創(chuàng)建Resources\View\Home\Index.zh-CN.resx,要么創(chuàng)建Resources\View.Home.Index.zh-CN.resx。同理,對Shared\_Layout.cshtml的本地化文件要放在Resources\View\Shared\_Layout.zh-CN.resxResources\View.Shared._Layout.zh-CN.resx,如下圖所示。

ASP.NET Core如何實現(xiàn)從文本文件讀取本地化字符串

自定義本地化文件

從上文可以知道,IViewLocalizer 接口負(fù)責(zé)從resx資源文件尋找本地化文本。如果要從其他位置尋找本地化文本,則需要自定義一個實現(xiàn)的IHtmlLocalizer或IStringLocalizer的類。IHtmlLocalizer會對文本參數(shù)進(jìn)行HTML編碼,因此推薦實現(xiàn)它。事實上,本地化控制器所需的類實現(xiàn)的則是IStringLocalizer。

假設(shè)我們想要從D:\Documents\Paradox Interactive\Stellaris\mod\cn\localisation\l.Chinese (Simplified).yml讀取文本,其內(nèi)容為

 NO_LEADER "無領(lǐng)袖"
 admiral "艦隊司令"
 nomad_admiral "$admiral$"
 ADMIRALS "艦隊司令"
 general "將軍"
 scientist "科學(xué)家"
 governor "總督"
 ruler "統(tǒng)治者"

一行的開頭是鍵名,空格后是本地化字符串。

public class YamlStringLocalizer : IHtmlLocalizer
{
 private readonly Dictionary languageDictionary = new Dictionary();

 public LocalizedString GetString(string name) { throw new NotImplementedException(); }

 public LocalizedString GetString(string name, params object[] arguments) { throw new NotImplementedException(); }

 public IEnumerable GetAllStrings(bool includeParentCultures) { throw new NotImplementedException(); }

 public IHtmlLocalizer WithCulture(CultureInfo culture) { throw new NotImplementedException(); }

 public LocalizedHtmlString this[string name]
 {
 get
 {
 var ci = CultureInfo.CurrentCulture;
 var languageName = ci.IsNeutralCulture ? ci.EnglishName : ci.Parent.EnglishName;

 var path = @"D:\Documents\Paradox Interactive\Stellaris\mod\cn\localisation\l.${languageName}.yml";
 if (languageDictionary.TryGetValue(languageName, out var content) == false)
 {
 if (File.Exists(path) == false)
  return new LocalizedHtmlString(name, name, true, path);

 content = File.ReadAllText(path);
 languageDictionary.Add(languageName, content);
 }

 var regex = new Regex(@"^\s*" + name + @":\s+""(.*?)""\s*$", RegexOptions.Multiline);
 var match = regex.Match(content);
 if (match.Success)
 {
 var value = match.Groups[1].Value;
 return new LocalizedHtmlString(name, value);
 }
 else
 {
 return new LocalizedHtmlString(name, name, true, path);
 }
 }
 }

 public LocalizedHtmlString this[string name, params object[] arguments] => throw new NotImplementedException();

}

代碼很簡單,讀取l.yml的所有文字,保存在緩存中,然后用正則表達(dá)式匹配鍵。

在視圖里,我們需要改用YamlStringLocalizer。

@inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer Lo
@inject YamlStringLocalizer YLo

但是YamlStringLocalizer還沒有向依賴注入注冊,所以還要把Startup.ConfigureServices()改成

public void ConfigureServices(IServiceCollection services)
{
 services.AddSingleton();

 services.AddMvc()
 .AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix,
   opt => { opt.ResourcesPath = "Resources"; })

 ......
}

感謝各位的閱讀!關(guān)于“ASP.NET Core如何實現(xiàn)從文本文件讀取本地化字符串”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI