前言
站點 A (UTF-8) 表單提交到站點 B (GB2312) 導致 `Request.Form` 亂碼。修改 `web.config` `requestEncoding` 無效,因 IIS 已按目標站點編碼解析請求體。正解:**在發送端 (站點 A) 設置 `Response.ContentEncoding` 強制輸出目標編碼**,接收端自動正確解碼。
錯誤嘗試與原因
| 嘗試 | 代碼 | 失效原因 |
| 修改接收端 web.config | `` | 請求已按 GB2312 解析完畢,無法逆向修正 |
| 接收端 Page_Load 設置 Request.ContentEncoding | `Request.ContentEncoding = Encoding.UTF8` | 請求流已讀取完畢,屬性只讀/無效 |
| 發送端 form accept-charset | ` | 瀏覽器支持不一致,不可靠 |
正確解決方案:發送端強制編碼
核心代碼 (站點 A 頁面)
protected void Page_Load(object sender, EventArgs e)
{
// 關鍵:強制響應輸出編碼為 GB2312,瀏覽器按此編碼提交表單
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
// 可選:同時設置頁面聲明編碼,雙重保險
Response.Charset = "GB2312";
}
原理圖解
站點 A (UTF-8 頁面)
→ Page_Load 設置 Response.ContentEncoding = GB2312
→ 響應頭 Content-Type: text/html; charset=GB2312
→ 瀏覽器解析頁面,表單提交時按 GB2312 編碼字段值
→ HTTP 請求體為 GB2312 字節流
→ 站點 B (GB2312 配置) 按默認編碼正確解析 Request.Form
→ ✅ 無亂碼
完整示例:跨站點搜索跳轉
站點 A: Search.aspx (UTF-8)
<%@ Page Language="C#" ContentType="text/html; charset=utf-8" %>
<form id="form1" runat="server" method="post" action="https://siteB.com/Result.aspx">
關鍵詞:<asp:TextBox ID="txtKey" runat="server" />
<asp:Button ID="btnGo" runat="server" Text="搜索站點B" OnClick="btnGo_Click" />
</form>
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
Response.Charset = "GB2312";
}
protected void btnGo_Click(object sender, EventArgs e)
{
// 也可這裡設置,但 Page_Load 更早生效
// Response.Redirect 會丟失 POST,這裡用 form action 直接提交
}
站點 B: Result.aspx (GB2312)
<%@ Page Language="C#" ContentType="text/html; charset=gb2312" %>
protected void Page_Load(object sender, EventArgs e)
{
string key = Request.Form["txtKey"]; // ✅ 正確獲取中文
// 業務邏輯...
}
進階:AJAX 跨域提交
// 站點 A 頁面
$.ajax({
url: "https://siteB.com/Api/Search",
type: "POST",
data: { key: $("#txtKey").val() },
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=GB2312");
},
// jQuery 內部會按 charset 編碼 data
});
// 站點 B 全局處理 (Global.asax)
protected void Application_BeginRequest()
{
if (Request.ContentType.Contains("charset=GB2312"))
{
Request.ContentEncoding = Encoding.GetEncoding("GB2312");
}
}
編碼選型建議
| 場景 | 推薦編碼 | 理由 |
| 新系統全鏈路 | UTF-8 | 國際標準、無兼容性問題 |
| 對接舊 GB2312 系統 | 發送端強制 GB2312 | 零改動舊系統、最低風險 |
| API 服務 | UTF-8 + Content-Type 標註 charset | REST 標準、跨語言互操作 |
總結
跨站點編碼不一致導致 `Request.Form` 亂碼,**核心原則:發送端決定提交編碼**。在發送頁面 `Page_Load` 設置 `Response.ContentEncoding = Encoding.GetEncoding("目標編碼")`,瀏覽器將按此編碼提交表單,接收端按自身配置正確解析。避免在接收端修改 `Request` 編碼 (已晚)、避免依賴 `accept-charset` (瀏覽器差異大)。新系統統一 UTF-8 徹底杜絕此類問題。
- 上一篇文章: Visual Studio 2010 必裝擴展插件精選:提升編碼效率的 3 款神器
- 下一篇文章: ASP.NET Cache 緩存操作封裝類:添加、移除、清空、鍵管理
Copyright ©
程式碼之家 All Rights Reserved