2016-03-09 50 views
3

是什麼 UrlPathEncode與以UrlEncode

HttpUtility.UrlEncode(params); 

我看了一下MSDN頁
https://msdn.microsoft.com/en-us/library/system.web.httputility.urlpathencode(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode(v=vs.110).aspx

,但它只是告訴你,不是

HttpUtility.UrlPathEncode(params); 

之間的區別要使用UrlPathEncode,它不會告訴它們有什麼不同。

+0

的可能的複製[HttpServerUtility.UrlPathEncode VS HttpServerUtility.UrlEncode](http://stackoverflow.com/questions/4145823/httpserverutility-urlpathencode-vs-httpserverutility-urlencode) – avs099

+0

HTTP的可能的複製:// stackoverflow.com/questions/7997934/in-asp-net-why-is-there-urlencode-and-urlpathencode – bodman

回答

3

你可以參考this

不同的是所有在空間逃逸。 UrlEncode將它們轉義爲+符號,UrlPathEncode轉義爲%20。 +和%20只有在它們是每個W3C的QueryString部分的一部分時纔是等價的。所以你不能使用+符號來逃避整個URL,只能查詢字符串部分。

2

的區別是串的一個編碼地址和一個編碼路徑部分(這意味着URL的查詢串之前的部分)從地址,在這裏是如何看起來實現:

/// <summary>Encodes a URL string.</summary> 
/// <returns>An encoded string.</returns> 
/// <param name="str">The text to encode. </param> 
public static string UrlEncode(string str) 
{ 
    if (str == null) 
    { 
     return null; 
    } 
    return HttpUtility.UrlEncode(str, Encoding.UTF8); 
} 

這裏是實現UrlPathEncode的:

/// <summary>Encodes the path portion of a URL string for reliable HTTP transmission from the Web server to a client.</summary> 
/// <returns>The URL-encoded text.</returns> 
/// <param name="str">The text to URL-encode. </param> 
public static string UrlPathEncode(string str) 
{ 
    if (str == null) 
    { 
     return null; 
    } 
    int num = str.IndexOf('?'); // <--- notice this 
    if (num >= 0) 
    { 
     return HttpUtility.UrlPathEncode(str.Substring(0, num)) + str.Substring(num); 
    } 
    return HttpUtility.UrlEncodeSpaces(HttpUtility.UrlEncodeNonAscii(str, Encoding.UTF8)); 
} 

和MSDN還規定了HttpUtility.UrlEnocde

這些方法重載可用於編碼整個URL,包括查詢字符串值。