共用方式為


ResourceManager 和 ASP.NET

您也可以從 Web 應用程式,使用 ASP.NET 來存取 ResourceManager。這個小型應用程式的程式碼在 WorldDocs 子目錄中,重要的常式在 Global.asax 和 Default.aspx 檔案中。

第一個 WorldDocs 應用程式的使用者要求,載入 Global.asax,並且執行 Application_Onstart 副程式。接著,這個副程式使用靜態 CreateFileBasedResourceManager 方法建立資源管理員,從檔案 (而非組件) 載入文字架構資源 (前述範例程式也示範這個功能)。同時會將 ResourceManager 被指定到 Application 的 RM 變數。每個使用者要求都會執行 Application_BeginRequest 副程式,將使用者的文化特性 (由 Request.UserLanguages 屬性指定) 指定到目前 Web 伺服器上執行的執行線,請參閱下列程式碼。

清單 5. 使用 ResourceManager 為資源命名 (Global.asax)

void Application_OnStart() {
    Application["RM"] = 
        ResourceManager.CreateFileBasedResourceManager 
       ("mytext", Server.MapPath("resources") 
       + Path.DirectorySeparatorChar, null);
}

void Application_BeginRequest(Object sender, EventArgs args) {
    // For each request initialize the culture values with
    // the user language as specified by the browser.

    try {
        Thread.CurrentThread.CurrentCulture = new 
            CultureInfo(Request.UserLanguages[0]);
    }
    catch(Exception) {
        // provide fallback for not supported languages.
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    }

    Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}

載入頁面後就會指定動態資源,亦即這裡的 Default.aspx 中的 Page_InitPage_Load 副程式。Page_Init 會建立頁面範圍的 ResourceManager,並為它指定 ApplicationRM 變數。使用者變更語言選擇時,Page_Load 副程式可以自動回傳到伺服器,動態變更文化特性,請參閱下列程式碼。

清單 6. 使用 ResourceManager 為資源命名 (Default.aspx)

void Page_Init(Object sender, EventArgs args) {
    // Get the ResourceManager from the Application object.
    rm = (ResourceManager) Application["RM"];
    ...
}

void Page_Load(Object sender, EventArgs args) {
    String SelectedCulture = MyUICulture.SelectedItem.Text;
    if(! SelectedCulture.StartsWith("Choose")) {
        // If another culture was selected, use that instead.
        Thread.CurrentThread.CurrentCulture = new  
            CultureInfo(SelectedCulture);
        Thread.CurrentThread.CurrentUICulture = new  
            CultureInfo(SelectedCulture);
    }
}

最後要檢查的是實際傳回影像和字串資源的程式碼。

    <img src="Flags/<%=CultureInfo.CurrentCulture%>.jpg">
    <%=rm.GetString("greeting")%>

您可以根據使用者的文化特性程式碼來建置檔案規格,動態決定影像資源,字串資源則是使用 ResourceManager,從適當的 .resources 檔案,載入字串資源。