Server.URLEncode方法會在一個字串上應用URL的編碼規則, 包括逸出字元.
URLEncode會如下轉換字元:
- 空格( )會被轉換為加號(+)
- 非字母數字字元會被轉換為他們的十六進位表現形式
舉例:
<%Response.Write(Server.URLEncode("http://www.microsoft.com")) %>
輸出結果為
http%3A%2F%2Fwww%2Emicrosoft%2Ecom
HttpUtility.UrlEncode方法可以被用來編碼整個URL, 包括查詢字串值(query-string values). 諸如空格和其他的標點符號傳入HTTP stream的時候, 他們可能會被誤解析為流的結尾. URL encoding會把這些URL中不允許出現的字元轉換為等同的字元實體. URL decoding會執行逆操作.
你可以使用UrlEncode()方法或UrlPathEncode()方法. 然而, 這兩個方法的傳回值是不同的.
UrlEncode()方法會把空格轉換為加號(+).
UrlPathEncode()方法會把空格轉換為字串"%20", 這也是空格的十六進位的表示方式.
你應該在對URL中的path部分編碼時使用UrlPathEncode()方法, 這樣能確保不論在什麼平台或瀏覽器上執行解碼的時候, 都會得到一個合法的URL.
兩個方法的區別
他們之間沒有什麼具體的區別. Server.UrlEncode的存在是因為需要與經典的ASP相容.
HttpServerUtility.UrlEncode 會在內部調用HttpUtility.UrlEncode.
摘自MSDN:
URL encoding ensures that all browsers will correctly transmit text in URL strings. Characters such as a question mark (?), ampersand (&), slash mark (/), and spaces might be truncated or corrupted by some browsers. As a result, these characters must be encoded in <a> tags or in query strings where the strings can be re-sent by a browser in a request string.
UrlEncode is a convenient way to access the HttpUtility..::.UrlEncode method at run time from an ASP.NET application. Internally, UrlEncode uses HttpUtility..::.UrlEncode to encode strings.
Server.URLEncode Method
http://msdn.microsoft.com/en-us/library/ms525738.aspx
HttpUtility.UrlEncode Method (String)
http://msdn.microsoft.com/en-us/library/4fkewx0t.aspx
HttpServerUtility.UrlEncode Method (String)
http://msdn.microsoft.com/en-us/library/zttxte6w.aspx
Server.UrlEncode vs. HttpUtility.UrlEncode
http://stackoverflow.com/questions/602642/server-urlencode-vs-httputility-urlencode