UrlPathEncode 与 UrlEncode

UrlPathEncode vs. UrlEncode

有什么区别
HttpUtility.UrlPathEncode(params);

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

但它只告诉你不要使用UrlPathEncode,并没有告诉你有什么区别。

可以参考this

The difference is all in the space escaping. UrlEncode escapes them into + sign, UrlPathEncode escapes into %20. + and %20 are only equivalent if they are part of QueryString portion per W3C. So you can't escape whole URL using + sign, only querystring portion.

不同之处在于一个编码 Url 的字符串和一个编码来自 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:

These method overloads can be used to encode the entire URL, including query-string values.