What is the difference between: Urlencode, Escapeuristring and Escapedatastring

Asked

Viewed 958 times

16

And which of the three is equivalent to encodeURIComponent javascript?

String: 'apostrophe' "double quotes" Stackoverflow!

string teste = "'apóstrofo' \"aspas duplas\" StackOverflow!";
HttpUtility.UrlEncode(teste); // %27ap%c3%b3strofo%27+%22aspas+duplas%22+StackOverflow!
Uri.EscapeUriString(teste); // 'ap%C3%B3strofo'%20%22aspas%20duplas%22%20StackOverflow!
Uri.EscapeDataString(teste); // %27ap%C3%B3strofo%27%20%22aspas%20duplas%22%20StackOverflow%21

Looking at the three results I could not know exactly what the biggest difference between them apart from the EscapeUriString do not escape apostrophe.

2 answers

11


All these methods relate to RFC 2396, that defines the syntax of Uniform Resource Identifiers (or URI) and, in the case of Urlencode, also the RFC 1738 (defining Uniform Resource Locators, or Urls).

Urlencode

When to use: When you need to ensure that a URL is valid, or when you need to pass a URL as a parameter within another URL.
How it works: Converts all control or reserved characters defined in RFC 1738 for its coded equivalents, thus preventing markers such as whitespace (which could define the end of a resource’s name) or backslash (which could define a protocol or credentials, depending on the position) from being misinterpreted.

Escapeuristring

When to use: When you need to pass a URI instead of a URL.
How it works: Converts all characters (except those described as non-reserved in RFC 2396) for hexadecimal representation. (this behavior changes if Iris or IDN interpretation is enabled). Because the character set reserved for Uris is different from the set for Urls, some valid Urls can be misinterpreted (mainly by using the plus sign [+].)

Escapedatastring

When to use: When you need to pass data in a URI.
How it works: Performs the same transformations of EscapeUriString, but includes control characters considered valid for a URI in the conversion in order to allow the data to be correctly interpreted as content and not as identifiers.

You can find some conversion tables between formats here.

6

Urlencode Returns a string in which all non-alphanumeric characters except -_. are replaced with a percent sign (%) followed by two hexadecimal digits and coded spaces as a (+).

Ex.:

<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>

You use Escapeuristring if what you are "escaping" is a URI, and Escapedatastring anywhere else.

There are differences in how the two are coded...

More information here:

http://blogs.msdn.com/b/yangxind/archive/2006/11/09/don-t-use-net-system-uri-unescapedatastring-in-url-decoding.aspx

I found more information here:

http://blog.nerdbank.net/2009/05/uriescapedatapath-and.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.