HttpUitlity.UrlDecode(string)是如何工作的?

问题描述:

我正在使用HttpUtility.UrlDecode(string)。但是,当我尝试解码字符串"%ab"时,它会返回“ ”字符,从而产生问题。HttpUitlity.UrlDecode(string)是如何工作的?

+0

你有什么期望的输出? – usr

+1

为什么这是一个问题? '%ab'是'(char)171',它是“1/2”符号(根据http://www.asciitable.com/)。如果你得到“未知字符”的符号,那么你使用的字体(字体)没有那个符号......或者你的页面编码不正确。 – Dai

如果你看看这个link你可以看到你可以发送编码作为参数的功能。我会玩这个,很可能,你从函数获得的字符串编码不是UTF-8。

https://msdn.microsoft.com/en-us/library/adwtk1fy(v=vs.110).aspx

已被编码用于传输在URL为解码字符串转换为字符串。

URL编码参考:http://www.w3schools.com/tags/ref_urlencode.asp

其最有可能你试图解码和UTF8 URL“%AB%犯规参考任何东西 - 这就是为什么你得到了‘’字符数限制。它不知道用什么字符来解码。

如果您尝试这样的事情解码:“此%图20是%20A%20text”则回复:“这是一个文本”,因为20%=“space'字符

您可以找到执行的方法on the reference source page,它实质上对指定的URL执行每个字符的验证,并根据需要对其进行转换。

您现在面临的问题很可能与输出字符串的编码有关。由UrlDecode返回的字符可能会返回一个字符,该字符不会被显示字符串的编码支持,从而导致“怪异”字符。

为了完整起见,这里是整个方法:

internal string UrlDecode(string value, Encoding encoding) { 
     if (value == null) { 
      return null; 
     } 

     int count = value.Length; 
     UrlDecoder helper = new UrlDecoder(count, encoding); 

     // go through the string's chars collapsing %XX and %uXXXX and 
     // appending each char as char, with exception of %XX constructs 
     // that are appended as bytes 

     for (int pos = 0; pos < count; pos++) { 
      char ch = value[pos]; 

      if (ch == '+') { 
       ch = ' '; 
      } 
      else if (ch == '%' && pos < count - 2) { 
       if (value[pos + 1] == 'u' && pos < count - 5) { 
        int h1 = HttpEncoderUtility.HexToInt(value[pos + 2]); 
        int h2 = HttpEncoderUtility.HexToInt(value[pos + 3]); 
        int h3 = HttpEncoderUtility.HexToInt(value[pos + 4]); 
        int h4 = HttpEncoderUtility.HexToInt(value[pos + 5]); 

        if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0) { // valid 4 hex chars 
         ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4); 
         pos += 5; 

         // only add as char 
         helper.AddChar(ch); 
         continue; 
        } 
       } 
       else { 
        int h1 = HttpEncoderUtility.HexToInt(value[pos + 1]); 
        int h2 = HttpEncoderUtility.HexToInt(value[pos + 2]); 

        if (h1 >= 0 && h2 >= 0) {  // valid 2 hex chars 
         byte b = (byte)((h1 << 4) | h2); 
         pos += 2; 

         // don't add as char 
         helper.AddByte(b); 
         continue; 
        } 
       } 
      } 

      if ((ch & 0xFF80) == 0) 
       helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode 
      else 
       helper.AddChar(ch); 
     } 

     return Utf16StringValidator.ValidateString(helper.GetString()); 
    }