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; }