本文以示例形式分析了Asp.net中Response.Charset與Response.ContentEncoding的區(qū)別,。具體如下:
1.Response.Charset
ASP.NET 中示例:
<%@ Page CodePage=936 %>
CodePage 告訴 IIS 按什么編碼來讀取 QueryString,按什么編碼轉(zhuǎn)換數(shù)據(jù)庫中的內(nèi)容……
2.Response.ContentEncoding
獲取或設(shè)置輸出流的 HTTP 字符集。
Response.Charset
獲取或設(shè)置輸出流的 HTTP 字符集。微軟對(duì) ContentEncoding、Charset 的解釋是一字不差,其實(shí)可以這樣理解:ContentEncoding 是標(biāo)識(shí)這個(gè)內(nèi)容是什么編碼的,而 Charset 是告訴客戶端怎么顯示的。
我們可以做一個(gè)示例來理解:
示例1.
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");Response.Charset = "utf-8"; Response.Write("錯(cuò)新站長站");然后用瀏覽器打開網(wǎng)頁,可以發(fā)現(xiàn)是亂碼,可是用記事本查看源文件,又發(fā)現(xiàn)不是亂碼。這就說明了:ContentEncoding 是管字節(jié)流到文本的,而 Charset 是管在瀏覽器中顯示的。
示例2.
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");通過 Fidller,發(fā)現(xiàn) HTTP 頭中是:text/html; charset=gb2312。說明沒有指定 Charset 時(shí),就用 ContentEncoding 的 Charset 作為 charset。
示例3.
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");Response.Charset = "123-8";HTTP 頭中是:text/html; charset=123-8。網(wǎng)頁顯示正常,說明如果 charset 錯(cuò)誤,仍然以 ContentEncoding 的 Charset 作為 charset。
示例4.
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");Response.Charset = "";HTTP 頭中是:text/html;。HTTP 頭中沒有 charset,網(wǎng)頁顯示正常,說明 HTTP 頭中沒有 charset,仍然以 ContentEncoding 的 Charset 作為 charset。
補(bǔ)充:
一.Response.ContentType
獲取或設(shè)置輸出流中 HTTP 的 MIME 類型,比如:text/xml、text/html、application/ms-word。瀏覽器根據(jù)不同的內(nèi)容啟用不同的引擎,比如 IE6 及以上版本中就會(huì)自動(dòng)將 XML 做成樹狀顯示。
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
這是 HTML 中的標(biāo)簽,不能用在 XML、JS 等文件中,它是告訴瀏覽器網(wǎng)頁的 MIME、字符集。當(dāng)前面的相關(guān)內(nèi)容沒有指定時(shí),瀏覽器通過此來判斷。
二.使用流形成一個(gè)word文件例子
protected void btnResponseWord_Click(object sender, EventArgs e){ Response.Clear(); //清空無關(guān)信息 Response.Buffer= true; //完成整個(gè)響應(yīng)后再發(fā)送 Response.Charset = "GB2312";//設(shè)置輸出流的字符集-中文 Response.AppendHeader("Content-Disposition","attachment;filename=Report.doc");//追加頭信息 Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//設(shè)置輸出流的字符集 Response.ContentType = "application/ms-word ";//輸出流的MIME類型 Response.Write(TextBox1.Text); Response.End();//停止輸出}
新聞熱點(diǎn)
疑難解答
圖片精選