ASP.NET的字符编码问题

 

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值