SimonD
SimonD

Reputation: 1547

System.Net.WebUtility.UrlEncode and System.Web.HttpUtility.UrlEncode methods differences

According to the documentation of the System.Net.WebUtility.UrlEncode(String) method character codes should be encoded with low-case letters, at least in the example it's stated so: "For example, when embedded in a block of text to be transmitted in a URL, the characters < and > are encoded as %3c and %3e." But I get all of them in upper case. For example this code:

string url = "https://host<test>";
Console.WriteLine("system.net: {0}", System.Net.WebUtility.UrlEncode(url);

Gives me the following:

system.net: https%3A%2F%2Fhost%3Ctest%3E

On the other side System.Web.HttpUtility.UrlEncode gives me all in low case:

string url = "https://host<test>";
Console.WriteLine("system.web: {0}", System.Web.HttpUtility.UrlEncode(url);

Output:

system.web: https%3a%2f%2fhost%3ctest%3e

Is it expected?

Upvotes: 1

Views: 589

Answers (1)

Rahul
Rahul

Reputation: 77926

Is it expected?

Looks like it is expected. Going through the source code WebUtility I see that public UrlEncode calls one of the private one

    public static string UrlEncode(string value)
    {
      // code stripped
        return Encoding.UTF8.GetString(UrlEncode(bytes, 0, bytes.Length, false /* alwaysCreateNewReturnValue */));
    }

    //private one makes a call to IntToHex
    private static byte[] UrlEncode(byte[] bytes, int offset, int count)
    {
      expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf);

    // IntToHex casting to uppercase character, reason being every 
    // encoded character is returning as uppercase.
    private static char IntToHex(int n)
    {
       //code stripped
        else
            return (char)(n - 10 + (int)'A');  //here
    }

Upvotes: 2

Related Questions