Should I use Replace () instead of HtmlEncode ()?

Should HtmlEncode () be abandoned and replaced () instead of me parsing links in posts / comments (with regex)? HtmlEncode () replaces & which I suppose might cause referencing problems, should I just use Replace () to replace <with & lt ;?

For example, if a user writes something like:
See this site http://www.somesite.com/somepage.aspx?qs1=1&qs2=2&qs3=3

I want it to be:
See this site <a href = "http://www.somesite.com/somepage.aspx?qs1=1&qs2=2&qs3=3"> http://www.somesite.com/somepage .aspx? qs1 = 1 & qs2 = 2 & qs3 = 3 </ a & gt ;

But with HtmlEncode () the url becomes (note the ampersand):
See this site http://www.somesite.com/somepage.aspx?qs1=1&qs2=2&qs3=3

Is it possible to avoid the problem by using the Replace () link instead?

thank

+1


source to share


5 answers


Actually, your last example - the one you're worried about - is the only correct one. In HTML documents, ampersands are used to introduce entity references and therefore must be escaped. While most browsers are forgiving enough to let them slip when they are not explicitly part of an entity reference, you can run into difficult problems if using them in a URL looks like an entity.



Let him HtmlEncode()

do his job.

+4


source


Are you looking for UrlEncode ()? http://msdn.microsoft.com/en-us/library/zttxte6w.aspx



+1


source


What do you want to replace and why? HtmlEncode () is commonly used to sanitize user supplied data. However, if you allow users to submit links, you probably don't want to HtmlEncode them in the first place. You are basically going to render them exactly the same as the user provided them.

0


source


Replacing and using & inside the attribute href

. If you don't, then your code is technically invalid. Also, you should avoid it even if it is inside a link. The only case you will run into is if you end up HTMLEncoding it multiple times.

0


source


I recommend not using Replace to execute HTMLEncode or URLEncode. These functions are designed specifically to address most of the problems you see in user-submitted content, and if you try to replace them with your own code, the results can be ugly (I'm speaking from experience here) if you forget something vital.

0


source







All Articles