如何在C#中使用URL(RFC 1738)标准对字符串进行编码?
以下在线工具可将字符串转换为此标准:http://www.freeformatter.com/url-encoder.html
我想要转换的字符串示例是test(brackets)
,编码后的字符串应该如下:
test%28brackets%29
如何在C#中使用URL(RFC 1738)标准对字符串进行编码?
以下在线工具可将字符串转换为此标准:http://www.freeformatter.com/url-encoder.html
我想要转换的字符串示例是test(brackets)
,编码后的字符串应该如下:
test%28brackets%29
Uri.EscapeDataString
可以实现你想要的功能,详见 MSDN。
Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.
无论是 HttpUtility.UrlEncode
还是 WebUtility.UrlEncode
都不会对这些字符进行编码,因为标准规定括号 ()
可以不编码使用。
我不知道你提供的 URL Encoder / Decoder 为什么会对它们进行编码,因为它也将它们列为可以在 URL 中使用的字符之一。
Uri.EscapeDataString
会使用 Uri 标准来转换字符串,但这并不符合 RFC 1738 标准。
RFC 1738 是一个旧的 URL 标准。
我使用 FormUrlEncodedContent
来完成它:
data = new List<KeyValuePair<string, string>>();
data.Add(new KeyValuePair<string, string>("key", "value"));
var payloadBody = await new FormUrlEncodedContent(data).ReadAsStringAsync();
如果您不需要编码的URL body,那么您可能需要在键/值上进行一些技巧操作,例如让值为空。