Server.URLEncode和HttpUtility.UrlEncode

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.