protected void Page_Load( object sender, EventArgs e) { Response.ContentEncoding = Encoding.GetEncoding( " gb2312 " ); // Request.ContentEncoding = Encoding.GetEncoding("gb2312"); //設定是無效的 }
這樣每次回應我們都是用的gb2312,依照asp.net預設requset物件初始化時編碼為utf-8,我們在文字方塊輸入中文,再點button按鈕時,request編碼為utf-8,response編碼為gb2312 ,所以造成文字方塊資料回發的時候變成了亂碼(文字方塊中文部分顯示一串問號)
protected override void InitializeCulture() { base .InitializeCulture(); Request.ContentEncoding = Encoding.GetEncoding( " gb2312 " ); }
解決方法二:取得表單資料字串,自己解析
Encoding encoding = Encoding.GetEncoding( " gb2312 " ); //自選解碼方式 Stream resStream = Request.InputStream; //接收的表單都是放這裡的 byte [] content = new byte [resStream.Length]; resStream.Read(content, 0 , content.Length); string postQuery = encoding.GetString(content); // NameValueCollection resDic = HttpUtility.ParseQueryString(postQuery, encoding); //解決編碼方式問題,預設還是會自動解碼
下面給出簡單的解析方法:
/// <summary> ///解析查詢字串/// </summary> /// <param name="postQuery"></param> /// <returns></returns> private NameValueCollection GetFormParams( string postQuery) { NameValueCollection result = new NameValueCollection(); string [] nameValueList = postQuery.Split( ' & ' ); foreach ( string item in nameValueList) { if (item.Contains( ' = ' )) { string [] nameValue = item.Split( ' = ' ); result.Add(nameValue[ 0 ], nameValue[ 1 ]); } } return result; }