以前解决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/>,欢迎来到<%="蓝色经典blueidea"%>。
ps.如果web.config中有
<globalization requestencoding="gb2312" responseencoding="gb2312" fileencoding="gb2312"/>
可省略
response.contentencoding=encoding.getencoding(936);
cs 源代码和dll:
g2bfilter.zip
dll直接拷到应用程序的bin目录即可调用