這篇文章給大家分享的是有關ASP.NET Core如何實現從文本文件讀取本地化字符串的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
實施全球化和本地化
國際化涉及全球化和本地化。 全球化是設計支持不同區域性的應用程序的過程。 全球化添加了對一組有關特定地理區域的已定義語言腳本的輸入、顯示和輸出支持。
本地化是將已經針對可本地化性進行處理的全球化應用調整為特定的區域性/區域設置的過程。 有關詳細信息,請參閱本文檔鄰近末尾的全球化和本地化術語。
應用本地化涉及以下內容:
使應用內容可本地化
為支持的語言和區域性提供本地化資源
實施策略,為每個請求選擇語言/區域性
全球化和本地化主要在兩個位置實施,一是控制器,二是視圖。在視圖里實施全球化和本地化,要在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文件夾尋找本地化資源文件。第二段代碼設置本應用程序支持的語言,似乎沒有簡單辦法說支持任何語言。
還需要在Startup.Configure()啟動請求本地化中間件。默認設置會從URL、Cookie、HTTP Accept-Language標頭讀取目標語言。
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>
現在先不添加資源文件,直接運行程序測試一下,程序會輸出Show following columns。這表明,如果ASP.NET Core找不到資源文件,會輸出鍵名。因此,微軟建議在ASP.NET Core,直接用自然語言作為鍵名。
然后添加資源文件。ASP.NET Core支持兩種資源文件組織方案。因為我們在AddViewLocalization時選擇了LanguageViewLocationExpanderFormat.Suffix,假設要對View\Home\Index.cshtml提供大陸簡體文本,要么創建Resources\View\Home\Index.zh-CN.resx,要么創建Resources\View.Home.Index.zh-CN.resx。同理,對Shared\_Layout.cshtml的本地化文件要放在Resources\View\Shared\_Layout.zh-CN.resx或Resources\View.Shared._Layout.zh-CN.resx,如下圖所示。

自定義本地化文件
從上文可以知道,IViewLocalizer 接口負責從resx資源文件尋找本地化文本。如果要從其他位置尋找本地化文本,則需要自定義一個實現的IHtmlLocalizer或IStringLocalizer的類。IHtmlLocalizer會對文本參數進行HTML編碼,因此推薦實現它。事實上,本地化控制器所需的類實現的則是IStringLocalizer。
假設我們想要從D:\Documents\Paradox Interactive\Stellaris\mod\cn\localisation\l.Chinese (Simplified).yml讀取文本,其內容為
NO_LEADER "無領袖"
admiral "艦隊司令"
nomad_admiral "$admiral$"
ADMIRALS "艦隊司令"
general "將軍"
scientist "科學家"
governor "總督"
ruler "統治者"
一行的開頭是鍵名,空格后是本地化字符串。
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的所有文字,保存在緩存中,然后用正則表達式匹配鍵。
在視圖里,我們需要改用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"; })
......
}感謝各位的閱讀!關于“ASP.NET Core如何實現從文本文件讀取本地化字符串”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。