以前解决gb2312/big5实时转换的做法一般是修改Response.ContentEncoding
string switchLanguage(String strLanguage){
if(strLanguage.StartsWith("zh-cn")){
Response.ContentEncoding=Encoding.GetEncoding(936);
return "gb2312";
}
if(strLanguage.StartsWith("zh")){
Response.ContentEncoding=Encoding.GetEncoding(950);
return "big5";
}
Response.ContentEncoding=Encoding.GetEncoding(1252);
return "iso-8859-1";
}
范例:
switchLanguage(Request.UserLanguages[0]);
但有些GB2312简体字没有对应的Big5,所以需要先转换成繁体的Gb2312,再进行转换
如:“秋水无恨”的无,“中国”的国,就会显示“秋水?恨”和“中?”
等需要先转化为“秋水無恨”和“中國”,再转化为Big5。
而filter正好帮助我们实现实时切换,主要源代码如下(_sGB和_tGB是GB2312简繁体对应的库)。
public override void Write(byte[] buffer, int offset, int count)
{
Encoding e=Encoding.GetEncoding(936);
string str=e.GetString(buffer,offset,count);
for(int i=0;i<str.Length;i++){
int j=_sGB.IndexOf(str[i]);
if(j!=-1)str=str.Replace(_sGB[j],_tGB[j]);
}
e=Encoding.GetEncoding(System.Web.HttpContext.Current.Response.Charset);
_sink.Write(e.GetBytes(str), 0, e.GetByteCount(str));
}
范例:
<%@ Page Language="C#" %>
<script runat=server>
protected void Page_Load(Object sender, EventArgs ev)
{
Response.ContentEncoding=Encoding.GetEncoding(936);
if(Request["e"]!=null){
Response.Filter = new qswhFilter.g2bFilter(Response.Filter);
if(Request["e"]=="1")Response.Charset="big5";
}
userName.Text="秋水无恨(qiushuiwuhen)";
}
</script>
<asp:hyperlink runat=server NavigateUrl="g2bFilter.aspx" Text="Gb2312简体" />
<asp:hyperlink runat=server NavigateUrl="g2bFilter.aspx?e=0" Text="Gb2312繁体" />
<asp:hyperlink runat=server NavigateUrl="g2bFilter.aspx?e=1" Text="Big5繁体" />
hi,你好,我是<asp:label runat=server id=userName/>,欢迎来到<%="csdn中国程序员大本营"%>。
ps.如果web.config中有
<globalization requestEncoding="gb2312" responseEncoding="gb2312" fileEncoding="gb2312"/>
可省略
Response.ContentEncoding=Encoding.GetEncoding(936);
cs 源代码和dll:
http://www.blueidea.com/user/qswh/g2bFilter.zip
dll直接拷到应用程序的bin目录即可调用
本文地址:http://com.8s8s.com/it/it45867.htm