引用:
1、HttpUtility.UrlEncode,HttpUtility.UrlDecode是靜態方法,而Server.UrlEncode,Server.UrlDecode是實例方法。
2、Server是HttpServerUtility類的實例,是System.Web.UI.Page的屬性。
3、用HttpUtility.UrlEncode編碼后的字符串和用Server.UrlEncode進行編碼后的字符串對象不一樣
Server.UrlEncode 可以根據你頁面定義好的編碼方式進行編碼。
而 HttpUtility.UrlDecode則默認以utf8來編碼。 不然你需要自己指定編碼方式:
Encoding gb2312= Encoding.GetEncoding("gb2312");
string v5= HttpUtility.UrlEncode("溫州", gb2312);
而 Server.UrlDecode則默認調用web.config中<globalization />節點中指定來編碼
<globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN" />
string v3= Server.UrlEncode("溫州");
在對URL進行編碼時,該用哪一個?這兩都使用上有什么區別嗎?
測試:
string file="文件上(傳)篇.doc";
string Server_UrlEncode=Server.UrlEncode(file);
string Server_UrlDecode=Server.UrlDecode(Server_UrlEncode);
string HttpUtility_UrlEncode=System.Web.HttpUtility.UrlEncode(file);
string HttpUtility_UrlDecode=System.Web.HttpUtility.UrlDecode(HttpUtility_UrlEncode);
Response.Write("原數據:"+file);
SFun.WriteLine("Server.UrlEncode:"+Server_UrlEncode);
SFun.WriteLine("Server.UrlDecode:"+Server_UrlDecode);
SFun.WriteLine("HttpUtility.UrlEncode:"+HttpUtility_UrlEncode);
SFun.WriteLine("HttpUtility.UrlDecode:"+HttpUtility_UrlDecode);
輸出:
原數據:文件上(傳)篇.doc
Server.UrlEncode:%ce%c4%bc%fe%c9%cf%a3%a8%b4%ab%a3%a9%c6%aa.doc
Server.UrlDecode:文件上(傳)篇.doc
HttpUtility.UrlEncode:%e6%96%87%e4%bb%b6%e4%b8%8a%ef%bc%88%e4%bc%a0%ef%bc%89%e7%af%87.doc
HttpUtility.UrlDecode:文件上(傳)篇.doc
區別在於:HttpUtility.UrlEncode()默認是以UTF8對URL進行編碼,而Server.UrlEncode()則以系統默認的編碼對URL進行編碼。
在用 ASP.Net 開發頁面的時候, 我們常常通過 System.Web.HttpUtility.UrlEncode 和 UrlDecode 在頁面間通過 URL 傳遞參數. 成對的使用 Encode 和 Decode 是沒有問題的.
但是, 我們在編寫文件下載的頁面的時候, 常常用如下方法來指定下載的文件的名稱:
Response.AddHeader("Content-Disposition","attachment; filename="+ HttpUtility.UrlEncode(fileName, Encoding.UTF8));之所以轉換成 UTF8 是為了支持中文文件名.
這 時候問題就來了, 因為 HttpUtility.UrlEncode 在 Encode 的時候, 將空格轉換成加號('+'), 在 Decode 的時候將加號轉為空格, 但是瀏覽器是不能理解加號為空格的, 所以如果文件名包含了空格, 在瀏覽器下載得到的文件, 空格就變成了加號.
一個解決辦法是, 在 HttpUtility 的 UrlEncode 之后, 將 "+" 替換成 "%20"( 如果原來是 "+" 則被轉換成 "%2b" ) , 如:
fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);
fileName = fileName.Replace("+", "%20");
不明白微軟為什么要把空格轉換成加號而不是"%20". 記得 JDK 的 UrlEncoder 是將空格轉換成 "%20"的.
經檢查, 在 .Net 2.0 也是這樣.
上面是從別的地方拷貝的,寫得很好,我自己的一個程序中也遇到同樣的問題,默認aspx是以utf-8編碼的,
代碼段一: Response.AppendHeader("content-disposition", "attachment;filename=" + Server.UrlEncode("疑問文件.doc") + ""); 而web.config配置: <globalization requestEncoding="gb2312" responseEncoding="gb2312" culture="zh-CN"/> 這樣是亂碼,因為aspx默認使用utf-8格式,而Server.UrlEncode默認調用web.config中<globalization />的配置編碼; 解決辦法(1): 將web.config配置修改為: <globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="zh-CN"/> 不會出現亂碼; 解決辦法(2): 使用HttpUtility.UrlEncode編碼, Response.AppendHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("疑問文件.doc") + ""); 這樣不會出現亂碼,因為aspx默認使用utf-8格式,HttpUtility.UrlEncode默認也是utf-8編碼,HttpUtility.UrlEncode不調用web.config中<globalization />的配置, 如果需要另外指定編碼格式則 :HttpUtility.UrlEncode("疑問文件.doc",Encoding.ASCII)