What's the difference between: UrlEncode, EscapeUriString, and EscapeDataString

16

And which of the three is equivalent to encodeURIComponent of 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 is between them and EscapeUriString does not escape apostrophe.

    
asked by anonymous 24.07.2014 / 14:19

2 answers

11

All of these methods are relative to RFC 2396 , which defines the Uniform Resource Identifiers (URI) syntax and, in the case of UrlEncode, also the RFC 1738 (which defines 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 the reserved or control characters defined in the RFC 1738 to their encoded equivalents, thus avoiding markers such as white space (which could define the end of a resource's name) or the backslash (which could define a protocol or credentials depending on the position) are erroneously interpreted.

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 differs from the set for URLs, some valid URLs may be misinterpreted (especially with the use of the plus sign.)

EscapeDataString

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

You can find some conversion tables between formats here .

    
31.07.2014 / 17:45
6

a UrlEncode Returns a string in which all non-alphanumeric characters with the exception of -_. are replaced with a percent sign followed by two hexadecimal digits and spaces encoded as a (+) sign.

Ex:

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

You use EscapeUriString if what you're "escaping" is a URI, and EscapeDataString anywhere else.

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

More information here:

link

I found more information here:

link

    
24.07.2014 / 14:28