protected void Page_Load( object sender, EventArgs e) { Response.ContentEncoding = Encoding.GetEncoding( " gb2312 " ); // Request.ContentEncoding = Encoding.GetEncoding("gb2312"); // The setting is invalid }
In this way, we use gb2312 for every response. According to the asp.net default requset object, the encoding is utf-8 when initialized. When we enter Chinese in the text box and click the button button, the request encoding is utf-8 and the response encoding is gb2312. , so the text box data becomes garbled when sent back (the Chinese part of the text box displays a string of question marks)
protected override void InitializeCulture() { base .InitializeCulture(); Request.ContentEncoding = Encoding.GetEncoding( " gb2312 " ); }
Solution 2: Get the form data string and parse it yourself
Encoding encoding = Encoding.GetEncoding( " gb2312 " ); // Select the decoding method Stream resStream = Request.InputStream; // The received forms are placed here byte [] content = new byte [resStream.Length]; resStream.Read(content, 0 , content.Length); string postQuery = encoding.GetString(content); // NameValueCollection resDic = HttpUtility.ParseQueryString(postQuery, encoding); // Solve the encoding problem, it will still decode automatically by default
A simple analysis method is given below:
/// <summary> /// Parse query string /// </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; }