[转]Asp.Net url中文乱码

一般有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 转换)。一样要将传递的中文参数进行编码,在接收时再进行解码。 
传递 
< type="JavaScript/text"> 
function GoUrl() 

  var Name = "中文参数"; 
location.href = "B.aspx?Name="+escape(Name); 

接收 
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中文处理相关问题

    ASP.NET的中文乱码问题,归根结底都是因为使用编码方式不匹配造成的。因为常常需要通过URL字符串在不同页面间传递参数时遇到中文,必须进行编码和解码,否则传递的参数不正确。一般使用 Server.UrlEncode 和 Server.UrlDecode 就可以解决问题了,但是有时会遇到特殊情况:

需要设置如下的全局配置


以下参考某某作者,忘记了,不好意思

但是 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 编码(同样进行与之匹配的解码),这样问题解决!虽然经过两次编码,效率很低,但是也是特殊情况。

来源:http://blog.sina.com.cn/s/blog_865810200100t8lw.html

原文地址:https://www.cnblogs.com/seasons1987/p/3216881.html