C#.net地址传参汉字乱码解决方案

文章来自:网易博客

web.config文件:

<system.web><globalization requestEncoding="GB2312" responseEncoding="GB2312"/></system.web>

使用上面的语句就可以了。

其他方法:

asp.net默认的编码是UTF-8

js文件里的编码也是UTF-8

当你要在aspx页面上进行传中文参数时会出现乱码

-request.aspx接收参数页-

response.aspx传送参数页-

例一:a href=request.aspx?str=中国人/a

解决办法一:

1.可以和改webconfig的编码 如:

<location path=‘response.aspx‘>
<system.web> 
<globalization fileEncoding=‘gb2312‘ requestEncoding=‘gb2312‘ responseEncoding=‘gb2312‘ culture=‘zh-CN‘/>
</system.web>
</location>

解决办法二:

1.如果你不想动webconfig 你可以在response.aspx.cs“里面对参数进行编码 如:

response.aspx在页面上:
a href=request.aspx?str=%=str%/a
response.cs页面上:
声明一个变量str
public string str=中国人;
str= HttpUtility.UrlEncode(str,System.Text.Encoding.GetEncoding(GB2312));
//这时str已经是编码后的

2.而在request.aspx.cs文件中也要进行转换 如:

声明一个变量 System.Collections.Specialized.NameValueCollection gb2312=HttpUtility.ParseQueryString(Request.Url.Query,System.Text.Encoding.GetEncoding(GB2312));
string str=gb2312[str];
这里的str就是你要接收的中文。

例二

如果你想在js里面传送中文参数 如:
request.aspx?str=+encodeURI(中国人);
这样就不会出现乱码了

例三

就是我在cshn上找到的一个方法我也没试过,大家可以试一下
protected string GetQueryString(string sKey,System.Text.Encoding e)
{
string QueryString=Server.UrlDecode(System.Web.HttpUtility.UrlDecode(Request.ServerVariables[ QUERY_STRING ],e));
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(sKey+=([^$]*?)($) );
System.Text.RegularExpressions.Match m = reg.Match(QueryString);
if (m.Success) { return m.Result( $1 ); }
else return String.Empty;
}
//以上这个不受编码影响,只需知道原来传入的编码就可.

 

 

posted @ 2013-06-07 12:23  学海无涯1999  阅读(375)  评论(0)    收藏  举报