最近在做的系統(tǒng)中,碰到了一個(gè)問(wèn)題,交易系統(tǒng)采用的UTF-8編碼,而一些支持系統(tǒng)使用的是GB2312編碼。
不同編碼的頁(yè)面、腳本之間互相引用,就會(huì)產(chǎn)生亂碼的問(wèn)題,解決方法就是統(tǒng)一成一種編碼。 asp.net 中,如果要修改輸出頁(yè)面的編碼,可以通過(guò)修改web.config中以下配置信息
<globalization requestEncoding="utf-8" responseEncoding="utf-8" /> 以上只是修改整體的默認(rèn)編碼,如果只有某個(gè)頁(yè)的編碼需要修改,ASP.net 中則可以簡(jiǎn)單的使用下面代碼:
注:加到Page_Load()事件下面就可以了 Encoding gb2312 = Encoding.GetEncoding("gb2312"); Response.ContentEncoding = gb2312; 在非ASP.net 應(yīng)用中,可能你讀到的數(shù)據(jù)是UTF-8編碼,但是你要轉(zhuǎn)換為GB2312編碼,則可以參考以下代碼:
string utfinfo = "document.write(\"alert(‘你好么??‘);\");"; string gb2312info = string.Empty;
Encoding utf8 = Encoding.UTF8; Encoding gb2312 = Encoding.GetEncoding("gb2312");
// Convert the string into a byte[]. byte[] unicodeBytes = utf8.GetBytes(utfinfo); // Perform the conversion from one encoding to the other. byte[] asciiBytes = Encoding.Convert(utf8, gb2312, unicodeBytes); // Convert the new byte[] into a char[] and then into a string. // This is a slightly different approach to converting to illustrate // the use of GetCharCount/GetChars. char[] asciiChars = new char[gb2312.GetCharCount(asciiBytes, 0, asciiBytes.Length)]; gb2312.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0); gb2312info = new string(asciiChars);
當(dāng)然,其他各種編碼之間的轉(zhuǎn)換,跟上述代碼也類似的,就不描述了。
|