在asp.net开发中,其web.config中的编码配置默认的是 UTF-8,这个时候你如果在IE地址栏中直接输入参数中带有汉字的Url(例:http://localhost/test/test.aspx?id=我靠,这样真的可以啊。), 这时在后台代码中用Request["id"]接收到的就是乱码,甚至有时候接收不到值。
当然大家有一种解决方法是 在web.config中把 编码改为gb2312就行了。但是如果对于整个项目来说不能改为gb2312或者客户要求使用utf-8编码,这时候该怎么办呢?
下面是我自己试着写的两种方法(也是在我回别人贴子时写的,怕以后忘了,所以就搞到博客里来了^_^),只是为了测试功能,里面还不完善,如果谁有兴趣的话,可以完善一下:
方法1:
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!this.Page.IsPostBack)
{
Request.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
this.Page.RegisterStartupScript("submit","<script language=javascript>document.Form1.action='test.aspx?id='+escape(document.Form1.action);document.Form1.submit();</script>");
}
else
{
Response.Write(Request["id"]);
}
}
方法2:
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(Session["ybm"]==null)
{
//Request.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
StringBuilder sb = new StringBuilder();
sb.Append("<script language=javascript>" + Environment.NewLine);
sb.Append(" JumpUrl();" + Environment.NewLine);
sb.Append(" function JumpUrl()" + Environment.NewLine);
sb.Append(" {" + Environment.NewLine);
sb.Append(" var curUrl = location.href;" + Environment.NewLine);
sb.Append(" curUrlArr = curUrl.split(/"=/");" + Environment.NewLine);
sb.Append(" curUrl = curUrlArr[0] + /"=/" + escape(curUrlArr[1]);" + Environment.NewLine);
sb.Append(" location.href = curUrl;" + Environment.NewLine);
sb.Append(" }" + Environment.NewLine);
sb.Append("</script>" + Environment.NewLine);
this.Page.RegisterStartupScript("submit",sb.ToString());
Session["ybm"]="yes";
}
else
{
Session["ybm"]=null;
Response.Write(Request["id"]);
}
}