ASP.NET 內建多語言機制存在冗餘、維護困難等問題。本文提出模組化、自動繫結、支援前後台整合的完整方案。
利用 InitializeCulture() 重寫當前執行緒文化特性:
protected override void InitializeCulture() {
string lang = "en";
if (Session["Language"] != null) lang = Session["Language"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
}
資源檔命名規則:
OrderResource.resxOrderResource.zh-CN.resx、OrderResource.en-US.resx程式碼引用主資源檔:OrderResource.FieldRequired,執行緒文化特性切換時自動載入對應語言版本。
將 JS 訊息同樣放入資源檔(如 JSResource.resx),於 OnPreRenderComplete 序列化為 JSON 物件輸出至頁面:
public static Dictionary<string, string> JsonResources = new Dictionary<string, string>();
public static string GetJsonResource() {
string key = $"JSResource.{Thread.CurrentThread.CurrentCulture.Name}";
if (!JsonResources.ContainsKey(key)) {
JavaScriptSerializer serializer = new JavaScriptSerializer();
ResourceSet rs = JSResource.ResourceManager.GetResourceSet(
Thread.CurrentThread.CurrentCulture, true, true);
string json = $"[{serializer.Serialize(rs.OfType<DictionaryEntry>().ToDictionary(x => x.Key, x => x.Value))}]";
JsonResources.Add(key, json);
}
return JsonResources[key];
}
protected override void OnPreRenderComplete(EventArgs e) {
Page.ClientScript.RegisterStartupScript(Page.GetType(), "",
$"<script>var json=eval({GetJsonResource()}); JSResource=json[0];</script>");
}
前端直接使用:alert(JSResource.JSMsg);
靜態 Dictionary 快取序列化結果,避免每次請求重複序列化資源檔。