How to URL encode strings in C#

前端 未结 3 1666
日久生厌
日久生厌 2021-01-11 13:21

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.

相关标签:
3条回答
  • 2021-01-11 13:35

    Uri.EscapeDataString will convert the string using the Uri standrards, which is not RFC 1738 conform.

    RFC 1738 is an old URL standard.
    I accomplished it by using FormUrlEncodedContent:

    data = new List<KeyValuePair<string, string>>();
    data.Add(new KeyValuePair<string, string>("key", "value"));
    
    var payloadBody = await new FormUrlEncodedContent(data).ReadAsStringAsync();
    

    If you don`t need a encoded URL body you probably need to trick arround with the key / value f.e. let the value empty.

    0 讨论(0)
  • 2021-01-11 13:45

    Uri.EscapeDataString does what you want. See MSDN.

    0 讨论(0)
  • 2021-01-11 13:47

    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.

    0 讨论(0)
提交回复
热议问题