萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET QueryString 亂碼終極解決方案:GB2312 與 UTF-8 混合環境編碼轉換全攻略

問題根源

當 ASP.NET 網站頁面編碼為 **GB2312**,而前端 JavaScript (預設 UTF-8) 或外部 UTF-8 系統發送請求時,`Request.QueryString["param"]` 會因編碼不匹配產生亂碼。核心原因在於 ASP.NET 依據頁面 `<@ Page ResponseEncoding="gb2312" %>` 自動以 GB2312 解碼 QueryString 位元組。

方案一:前端 UrlEncode (UTF-8) + 後端 UrlDecode (UTF-8) —— 最推薦

前端 (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 解碼並解析。

方案三:統一網站編碼為 UTF-8 —— 根治

  • `Web.config`:``
  • 所有 `.aspx`、`ashx`、`js`、資料庫連線字串、資料表欄位編碼全面統一 UTF-8。
  • 新專案**強制建議**採用此方案,消除編碼地獄根源。

方案四:Post 表單提交 + 隱藏欄位傳遞編碼標記

<form method="post" action="accept.aspx">
    <input type="hidden" name="__encoding" value="utf-8" />
    <input type="text" name="name" />
    <input type="submit" />
</form>

後端讀取 `__encoding` 決定解碼方式,但較繁瑣,不推薦新專案使用。

常見誤區與補充

  • Request.Form 同樣受影響:POST 表單同樣依 `requestEncoding` 解碼,解決方案同理。
  • 不要使用 `Request.Url.Query`:該屬性已經過解碼,無法取得原始位元組。
  • IIS URL Rewrite 模組:可在伺服器層透過 `rewriteMap` 或規則強制轉碼,但維護成本高。
  • ASP.NET Core:預設統一 UTF-8,模型綁定自動處理,不存在此問題。

總結建議

場景推薦方案
新專案方案三:全站 UTF-8
維舊專案,可控前端方案一:前端 encodeURIComponent + 後端 UrlDecode(UTF8)
維舊專案,不可控前端 (第三方回調)方案二:反射取原始位元組重新解碼

徹底理解「位元組 → 編碼 → 字串」的轉換鏈路,並善用 `HttpUtility.UrlEncode/Decode` 指定編碼,是解決 ASP.NET 編碼亂碼的核心功力。

copyright © 萬盛學電腦網 all rights reserved