如何在C#中对字符串进行URL编码

rum*_*umi 12 c# encoding url-encoding

我们如何使用C#中的URL(RFC 1738)标准对字符串进行编码?

以下在线工具使用此标准http://www.freeformatter.com/url-encoder.html转换字符串

我要转换的字符串示例是test(brackets),编码的字符串应如下所示:

test%28brackets%29
Run Code Online (Sandbox Code Playgroud)

小智 18

Uri.EscapeDataString做你想要的.请参阅MSDN.

  • Uri.EscapeDataString的行为[随.NET 4.5更改](http://msdn.microsoft.com/en-us/library/hh367887%28v=vs.110%29.aspx)包含RFC 3986字符. (7认同)

Dir*_*irk 7

根据RFC 1738:

Thus, only alphanumerics, the special characters "$-_.+!*'(),", and
reserved characters used for their reserved purposes may be used
unencoded within a URL.
Run Code Online (Sandbox Code Playgroud)

HttpUtility.UrlEncode不会也不WebUtility.UrlEncode会对这些字符进行编码,因为标准规定括号()可以不加编码使用.

我不知道为什么你链接的URL编码器/解码器对它们进行编码,因为它还将它们列为可以在URL中使用的字符.