【发布时间】:2014-03-27 15:46:31
【问题描述】:
我们如何在 C# 中使用 URL (RFC 1738) 标准对字符串进行编码?
以下在线工具正在使用此标准 http://www.freeformatter.com/url-encoder.html 转换字符串
我要转换的字符串示例是test(brackets),编码后的字符串应如下所示:
test%28brackets%29
【问题讨论】:
标签: c# encoding url-encoding
我们如何在 C# 中使用 URL (RFC 1738) 标准对字符串进行编码?
以下在线工具正在使用此标准 http://www.freeformatter.com/url-encoder.html 转换字符串
我要转换的字符串示例是test(brackets),编码后的字符串应如下所示:
test%28brackets%29
【问题讨论】:
标签: c# encoding url-encoding
Uri.EscapeDataString 做你想做的事。见MSDN。
【讨论】:
根据RFC 1738:
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 将使用不符合 RFC 1738 的 Uri 标准转换字符串。
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,您可能需要使用键/值 f.e 来欺骗 arround。让值为空。
【讨论】: