[asp.net mvc]如何實做簡易多國語系(multi language)
先在專案加入App_GlobalResources資料夾,並且加入多個資源檔*.resx:
ps. 各個語系都有自己固定的名稱,例如:中文繁體就是zh-TW,英文就是en-US…請參考網路上的公認的命名原則,不要自創喔!
然後在任何一個Controller加入一個切換語系的Action:
public ActionResult ChangeLanguage(string lang)
{
Session["lang"] = lang;
return RedirectToAction("Index", "Home", new { language = lang });
}
接著在任一個view加入幾個href,下面例子是在_Layout.cshtml的menu裡面(此為bootrap4 的menu):
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<label id="lblMenuLanguage">@Resources.Content.lblMenuLanguage</label>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="~/Home/ChangeLanguage?lang=en">English</a>
<a class="dropdown-item" href="~/Home/ChangeLanguage?lang=zh-TW">繁體中文</a>
<a class="dropdown-item" href="~/Home/ChangeLanguage?lang=zh-CN">简体中文</a>
</div>
</li>
當然也不要忘記設定多語系.resx檔案:
有個關鍵點要注意的就是,.resx的屬性設定的CustomTool屬性,需設定為ResXFileCodeGenerator,並且下一步手動將他的權限設定為public,如下圖:
最後在Global.asax加入切換多國語系的程式碼:
//設定多國語言
protected void Application_AcquireRequestState(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
var languageSession = "en";
if (context != null && context.Session != null)
{
languageSession = context.Session["lang"] != null ? context.Session["lang"].ToString() : "en";
}
Thread.CurrentThread.CurrentUICulture = new CultureInfo(languageSession);
Thread.CurrentThread.CurrentCulture = new CultureInfo(languageSession);
}
就是這麼簡單,參考下圖簡易範例mvc網站截圖就是執行結果:
這篇大概是這樣…謝謝觀賞!
ps.如果最後發行到appharbor雲端,且出現App_GlobalResources/' is not allowed because the application is precompiled錯誤的時候,在appharbor官網設定此app的precompile選項關閉,然後重新發行一個無意義但是有修改過的版本(這樣可以讓他app重新啟動),應該這樣就可以正常讓多語系正常在appharbor運作了!
參考資料:
Multi Languages in ASP.NET MVC - Learn Programming with Real Apps (learningprogramming.net)
Navbar · Bootstrap (getbootstrap.com)
https://stackoverflow.com/questions/34314146/visual-studio-2015-cant-change-access-modifier-of-new-resources-files