I am trying to implement HttpUtility.HtmlEncode (). The string that this method will encode will be used for rendering into html. if it is encoded then how will it render correctly? do I need to decode it again before using it to render? In that case what is the point of encoding if we have to decode it again to render it correctly?
Asked
Active
Viewed 4,482 times
1
-
There's not nearly enough detail here to offer a proper answer. – Sam Axe Mar 30 '17 at 07:35
-
1It will render correctly because browsers understand that encoding. You don't need to decode it - encoding is used to *render* characters that can't be displayed in the original form – Panagiotis Kanavos Mar 30 '17 at 07:37
-
There are many usages to HTML encoding. Among them: avoiding security issues (think XSS). Also, showing HTML code to the user (preventing the browser from actually parsing it). – haim770 Mar 30 '17 at 07:38
-
I have a
- tag in the string that I am encoding. If I do not encode then it displays the text with bullet(as expected). However if I encode it, then it is not.
– SKTripathy Mar 30 '17 at 07:47
1 Answers
3
You should only encode it if you have arbitrary text you want to make sure it doesn't contain HTML elements. HtmlEncode
will make it render as text, rather than HTML.
If you don't want to do that, don't encode or decode.
For example, this string that was put in a text field by a lovely user of your application (assuming your framework doesn't prevent XSS injection for you already):
string s = "<script>alert('dangerous');</script>";
When it is put on the page without HtmlEncode
, it will show you the alert in a browser dialog (it executes the Javascript for that). If you call HtmlEncode
on it, it will render as text. The Javascript isn't executed.
<script>alert('dangerous');</script>

Patrick Hofman
- 153,850
- 22
- 249
- 325
-
Yes I am using this method to prevent a XSS error I got from beracode analysis. I have a
- tag along with the string that i am trying to encode. Post encoding the browser is not interpreting the bullet.
– SKTripathy Mar 30 '17 at 07:50 -
-
I guess OP wants something like html sanitizer, not completely encode whole html string. – Evk Mar 30 '17 at 07:52
-
-
@samirkumartripathy see [here](http://stackoverflow.com/q/1637275/993547) for example. – Patrick Hofman Mar 30 '17 at 07:54
-
@Patrick Hofman, Thanks a lot for pointing me in the right direction. :) – SKTripathy Mar 30 '17 at 08:38
-