How to get Uri.EscapeDataString to comply with RFC 3986

后端 未结 5 1432
死守一世寂寞
死守一世寂寞 2020-11-30 04:07

The Uri class defaults to RFC 2396. For OpenID and OAuth, I need Uri escaping consistent with RFC 3986.

From the System.Uri class documentation:

5条回答
  •  天涯浪人
    2020-11-30 04:27

    I could not find a better answer (either 100% framework or 100% reimplementation), so I've created this abomination. Seems to be working with OAuth.

    class al_RFC3986
    {
        public static string Encode(string s)
        {
            StringBuilder sb = new StringBuilder(s.Length*2);//VERY rough estimate
            byte[] arr = Encoding.UTF8.GetBytes(s);
    
            for (int i = 0; i < arr.Length; i++)
            {
                byte c = arr[i];
    
                if(c >= 0x41 && c <=0x5A)//alpha
                    sb.Append((char)c);
                else if(c >= 0x61 && c <=0x7A)//ALPHA
                    sb.Append((char)c);
                else if(c >= 0x30 && c <=0x39)//123456789
                    sb.Append((char)c);
                else if (c == '-' || c == '.' || c == '_' || c == '~')
                    sb.Append((char)c);
                else
                {
                    sb.Append('%');
                    sb.Append(Convert.ToString(c, 16).ToUpper());
                }
            }
            return sb.ToString();
        }
    }
    

提交回复
热议问题