System.Net.WebUtility.UrlEncode和System.Web.HttpUtility.UrlEncode方法的区别

时间:2019-06-25 07:31:54

标签: c# url

根据 System.Net.WebUtility.UrlEncode(String)方法的documentation,字符代码应使用小写字母编码,至少在示例中是如此:“ 例如,当嵌入要在URL中传输的文本块中时,字符<和>被编码为%3c和%3e。 但是我都用大写字母。例如此代码:

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

请给我以下内容:

  

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

另一方面, System.Web.HttpUtility.UrlEncode 以小写形式显示了所有内容:

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

输出:

  

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

是预期的吗?

1 个答案:

答案 0 :(得分:1)

  

是预期的吗?

看起来像预期的那样。通过源代码WebUtility,我看到公共UrlEncode调用了私有代码之一

    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
    }