user6038265
user6038265

Reputation:

UrlPathEncode vs. UrlEncode

What is the difference between

HttpUtility.UrlPathEncode(params);

AND

HttpUtility.UrlEncode(params);

I looked at the MSDN pages
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

but it only tells you not to use UrlPathEncode, it doesn't tell what the difference is.

Upvotes: 7

Views: 10760

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

The difference is one Encodes Url of string and one encodes Path portion (which means the portion of url before query string) from Url, Here is the implementation how it looks:

 /// <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);
 }

and here is implementation of 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));
}

and msdn also states for HttpUtility.UrlEnocde:

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

Upvotes: 7

Gerald Gonzales
Gerald Gonzales

Reputation: 533

You can refer to 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.

Upvotes: 1

Related Questions