ASP.NET的字符编码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/abc2222753/article/details/52400999
 

ASP.NET的字符编码问题真是搞得人头疼,其中的中文很容易产生各种乱码问题,而这些乱码归根结底都是因为使用编码方式不匹配造成的。

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

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

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

<configuration>
<system.web>
<!-- 全球化 此节设置应用程序的全球化设置。 -->
<globalization 
fileEncoding="gb2312"
requestEncoding="gb2312"
responseEncoding="utf-8"
/>
</system.web>
</configuration>


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

/// <summary>
/// 编码
/// </summary>
/// <param name="code_type"></param>
/// <param name="code"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 解码
/// </summary>
/// <param name="code_type"></param>
/// <param name="code"></param>
/// <returns></returns>
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;
}

猜你喜欢

转载自blog.csdn.net/abc2222753/article/details/52400999