2016-03-09 53 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,包括查询字符串值。