Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)归海一刀
published in(发表于) 2014/1/30 0:58:39
ASP.NET中url传递中文的解决方案_[Asp.Net教程]

ASP.NET中url传递中文的解决方案_[Asp.Net教程]

















一般有3种方法:
1.设置web.config文件

......

......

2.传递中文之前,将要传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递
string Name = "中文参数";
Response.Redirect("B.aspx?Name="+Server.UrlEncode(Name));
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));




3.如果是从 .HTML 文件向 .Aspx 文件进行传递中文参数的话(即不从后台用 Redirect()方法进行 Url 转换)。一样要将传递的中文参数进行编码,在接收时再进行解码。
>> 进行传递

onclick="GoUrl()">
>> 进行接收
string Name = Request.QueryString["Name"];
Response.Write(Server.UrlDecode(Name));




一般来说。设置web.config文件就可以了。但是如果你用 JavaScript 调用 webservice 方法的话(往webservice里面传递中文参数)。设置 web.config 文件好象无效。




或用




Response.Redirect("test1.aspx?111="+System.Web.HttpUtility.UrlEncode("中华人明共和国")); //建议使用







ASP.NET中Url中文处理相关问题
作者:砂子 2007-07-11 14:38:14
ASP.NET的字符编码问题真是搞得人头疼,其中的中文很容易产生各种乱码问题,而这些乱码归根结底都是因为使用编码方式不匹配造成的。




因为常常需要通过URL字符串在不同页面间传递参数时遇到中文,必须进行编码和解码,否则传递的参数不正确。




通常使用 Server.UrlEncode 和 Server.UrlDecode 就可以解决问题了,但是有时会遇到特殊情况:




因为某个组件的需要而设置如下的全局配置







fileEncoding="gb2312"
requestEncoding="gb2312"
responseEncoding="utf-8"
/>







但是 requestEncoding="gb2312" 使得url传递的中文无法通过Server.UrlEncode 和 Server.UrlDecode 正确编码和解码,于是只好使用了自定义的编码和解码方案:




///


/// 编码
///

///
///
///
static public string EnCodeBase64(string code_type,string code)
{
string encode = "";
if(code_type == null)
{
code_type = "unicode";
}
if(code != null && code.Length > 0)
{
byte[] bytes = System.Text.Encoding.GetEncoding(code_type).GetBytes(code);
try
{
encode = Convert.ToBase64String(bytes);
}
catch
{
//encode = code;
}
}
return encode;
}
///
/// 解码
///

///
///
///
static public string DeCodeBase64(string code_type,string code)
{
string decode = "";
if(code_type == null)
{
code_type = "unicode";
}
if(code != null && code.Length > 0)
{
try
{
decode = Encoding.GetEncoding(code_type).GetString(Convert.FromBase64String(code));
}
catch(Exception ex)
{
//Console.Write(ex.Message);
//decode = code;
}
}
return decode;
}







这样中文可以变成Base64形式避免了被ASP.NET错误转换,但是实际运行后发现还有问题:就是Base64码中包含加号+经过ASP.NET传递后会将+变成空格,导致Base64字符串被破坏。




于是考虑在经过EnCodeBase64编码后再次使用Server.UrlEncode 编码(同样进行与之匹配的解码),这样问题解决!




虽然经过两次编码,效率很低,但是也是特殊情况:)




来源:csdn

























If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759