在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"]);
}
}