當 ASP.NET 網站頁面編碼為 **GB2312**,而前端 JavaScript (預設 UTF-8) 或外部 UTF-8 系統發送請求時,`Request.QueryString["param"]` 會因編碼不匹配產生亂碼。核心原因在於 ASP.NET 依據頁面 `<@ Page ResponseEncoding="gb2312" %>` 自動以 GB2312 解碼 QueryString 位元組。
前端 (JavaScript):
var name = "張三";
var encoded = encodeURIComponent(name); // 輸出 UTF-8 百分比編碼 %E5%BC%B5%E4%B8%89
window.location.href = "accept.aspx?name=" + encoded;
後端 (C#):
string name = HttpUtility.UrlDecode(Request.QueryString["name"], Encoding.UTF8);
// 正確得到 "張三"
優點:跨編碼頁面通用、標準化、無需修改伺服器配置。
缺點:需雙方協議編碼規範。
利用反射存取內部 `Request.QueryStringBytes` 屬性,繞過 ASP.NET 自動解碼:
public static NameValueCollection GetRawQueryString(HttpRequest request, Encoding targetEncoding)
{
// 取得內部私有屬性 QueryStringBytes (byte[])
var type = request.GetType();
var prop = type.GetProperty("QueryStringBytes",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.IgnoreCase);
byte[] rawBytes = prop.GetValue(request, null) as byte[];
if (rawBytes == null || rawBytes.Length == 0)
return new NameValueCollection();
// 手動以指定編碼解碼完整 QueryString 字串
string rawQueryString = HttpUtility.UrlDecode(rawBytes, targetEncoding);
// 解析成 NameValueCollection
return HttpUtility.ParseQueryString(rawQueryString);
}
// 使用範例
var rawParams = GetRawQueryString(Request, Encoding.UTF8);
string name = rawParams["name"]; // 正確取得 UTF-8 解碼後的值
原理:`HttpRequest.FillInQueryStringCollection()` 內部使用 `this.QueryStringEncoding` (即頁面編碼) 解碼 `QueryStringBytes`。我們提前攔截原始位元組,自行以 UTF-8 解碼並解析。
<form method="post" action="accept.aspx">
<input type="hidden" name="__encoding" value="utf-8" />
<input type="text" name="name" />
<input type="submit" />
</form>
後端讀取 `__encoding` 決定解碼方式,但較繁瑣,不推薦新專案使用。
| 場景 | 推薦方案 |
|---|---|
| 新專案 | 方案三:全站 UTF-8 |
| 維舊專案,可控前端 | 方案一:前端 encodeURIComponent + 後端 UrlDecode(UTF8) |
| 維舊專案,不可控前端 (第三方回調) | 方案二:反射取原始位元組重新解碼 |
徹底理解「位元組 → 編碼 → 字串」的轉換鏈路,並善用 `HttpUtility.UrlEncode/Decode` 指定編碼,是解決 ASP.NET 編碼亂碼的核心功力。