How to URL encode strings in C#

2019-02-16 17:31发布

How can we encode a string using the URL (RFC 1738) standard in C#?

The following online tool is converting the strings using this standard http://www.freeformatter.com/url-encoder.html

An example of the string I want to convert is test(brackets) and the encoded string should look like:

test%28brackets%29

2条回答
戒情不戒烟
2楼-- · 2019-02-16 18:02

According to RFC 1738:

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

Neither HttpUtility.UrlEncode nor WebUtility.UrlEncode will encode those characters since the standard says the parentheses () can be used unencoded.

I don't know why the URL Encoder / Decoder you linked encodes them since it also lists them as as a character that can be used in a URL.

查看更多
Explosion°爆炸
3楼-- · 2019-02-16 18:14

Uri.EscapeDataString does what you want. See MSDN.

查看更多
登录 后发表回答