ASP.NET乱码解决方案
应用场景在URL传值和接收中很容易出现乱码,特找到解决方案如下:
1、在web.config文中<system.web>加入
<globalization requestEncoding="gb2312" responseEncoding="gb2312" />
2、对传递的URL进行GB2312编码
public string InitChineseUrl(string chineseUrl)
{
Uri url = new Uri(chineseUrl);
System.Collections.Specialized.NameValueCollection nv = System.Web.HttpUtility.ParseQueryString(url.Query, System.Text.Encoding.GetEncoding("utf-8"));
string query = "";
for (int i = 0; i < nv.Count; i++)
{
if (query.Trim() == string.Empty)
{
query = "?" + nv.Keys[i] + "=" + HttpUtility.UrlEncode(nv[i], System.Text.Encoding.GetEncoding("GB2312"));
}
else
{
query += "&" + nv.Keys[i] + "=" + HttpUtility.UrlEncode(nv[i], System.Text.Encoding.GetEncoding("GB2312"));
}
}
string u = chineseUrl.Split('?')[0] + query;
return u;
}