資源檔架構
App_GlobalResources/
Resources.resx (預設/fallback)
Resources.en-US.resx (英文)
Resources.zh-TW.resx (繁體中文)
App_LocalResources/
Default.aspx.resx
Default.aspx.en-US.resx
Default.aspx.zh-TW.resx
資源檔內容範例
| Name (Key) | Resources.resx (預設) | Resources.en-US.resx |
| pagefile | 全域資源測試 | Global Resource Test |
| Question | 今天是今年的第幾天? | What day of year is today? |
| Answer | 距離今年結束還有 {0} 天 | Days left this year: {0} |
頁面啟用自動文化特性
<%@ Page Language="C#" Culture="Auto" UICulture="Auto" %>
Culture="Auto":影響日期、數字、貨幣格式 (Thread.CurrentThread.CurrentCulture)。
UICulture="Auto":影響資源檔選擇 (CurrentUICulture)。
- ASP.NET 依據瀏覽器
Accept-Language 標頭自動設定。
後端程式碼存取資源
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
// 強型別存取全域資源 (需專案屬性啟用 "Generate strongly typed resources")
Page.Title = Resources.Resource.pagefile;
Response.Write(Resources.Resource.Question + "<br/>");
}
protected void btnCalc_Click(object sender, EventArgs e) {
int days = DateTime.Now.DayOfYear - cal.SelectedDate.DayOfYear;
int left = days > 0 ? 365 - days : Math.Abs(days);
// 使用 string.Format 配合資源字串佔位符
lblResult.Text = string.Format(Resources.Resource.Answer, left);
}
}
前端宣告式繫結
<asp:Label ID="lblTitle" runat="server" Text="<%$ Resources:Resource, pagefile %>" />
<asp:Button ID="btn" runat="server" Text="<%$ Resources:Resource, ButtonText %>" />
本地資源存取
// 後端
string local = (string)GetLocalResourceObject("LocalKey");
// 前端
<asp:Literal Text="<%$ Resources:LocalKey %>" />
瀏覽器語言設定測試
- Chrome:設定 → 語言 → 新增「English (United States)」並移至最上方。
- Firefox:選項 → 語言 → 選擇 English/United States。
- Edge/IE:網際網路選項 → 語言 → 新增 en-US。
- 重新整理頁面,觀察資源切換。
進階:手動切換語言
protected void ddlLang_SelectedIndexChanged(object sender, EventArgs e) {
string lang = ddlLang.SelectedValue; // "zh-TW", "en-US"
HttpCookie cookie = new HttpCookie("UserLang", lang) { Expires = DateTime.Now.AddYears(1) };
Response.Cookies.Add(cookie);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
Server.Transfer(Request.Path); // 重新載入頁面套用新文化特性
}
// Global.asax Application_BeginRequest 統一套用
void Application_BeginRequest(object sender, EventArgs e) {
var cookie = Request.Cookies["UserLang"];
if (cookie != null) {
var ci = new CultureInfo(cookie.Value);
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}
}
資源檔管理工具
- Visual Studio 內建編輯器(雙擊 .resx)。
- ResX Resource Manager (VS 擴充套件):樹狀檢視、缺漏鍵值偵測、匯入/匯出 Excel/CSV 供翻譯人員使用。
- 建置後事件自動執行
resgen.exe 驗證格式。
常見問題
| 現象 | 原因 | 解決 |
| 資源不切換 | 未設定 Culture="Auto" 或瀏覽器語言未支援 | 檢查 @Page 指示詞、瀏覽器 Accept-Language、對應 .resx 是否存在 |
| 強型別類別未產生 | 專案屬性未啟用 | 專案右鍵 Properties → Resources → 勾選 "Generate strongly typed resources" |
| 日期格式未跟著變 | Culture vs UICulture 混淆 | Culture 控制格式,UICulture 控制資源,兩者皆設 Auto |
| App_GlobalResources 找不到 | 網站專案 vs Web 應用程式專案路徑不同 | 網站專案放根目錄,Web 應用程式專案需放在專案根目錄並設為 Embedded Resource |