首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 多語言實作:後台訊息、前台 JS 與頁面自動繫結整合方案

     編輯:關於ASP.NET

ASP.NET 內建多語言機制存在冗餘、維護困難等問題。本文提出模組化、自動繫結、支援前後台整合的完整方案。

理想多語言框架特性

  • 模組化解決資料冗餘(非全域資源檔)
  • 頁面與資源檔自動對應,減少人工維護
  • 支援後台訊息與前台 JavaScript 訊息雙語系

後台訊息多語言實作

利用 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.resx
  • 其他語言:OrderResource.zh-CN.resx、OrderResource.en-US.resx

程式碼引用主資源檔:OrderResource.FieldRequired,執行緒文化特性切換時自動載入對應語言版本。

前台 JavaScript 多語言實作

將 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 快取序列化結果,避免每次請求重複序列化資源檔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved