Yes, it protects you from XSS when writing to an HTML document, but you should use the HtmlTextWriter.WriteEncodedText method.
' Assign a value to a string variable, ' encode it, and write it to a page. colHeads = "<custID> & <invoice#>" writer.WriteEncodedText(colHeads) writer.WriteBreak()
displays
<custID> & <invoice
into the stream.
Note that using <%: and WriteEncodedText applicable only for output to the HTML context. They should not be used in JavaScript output:
<script> var myVariable = '<%: thisIsWrong %>'; </script>
In this context, HttpUtility.JavaScriptStringEncode should be used (with brackets <%= %> to prevent HTML from coding incorrectly). This function also correctly encodes special characters, so if </script> should appear in the script tag when trying to close the HTML script tag, ready for an XSS attack, it will display as:
\u003c/script\u003e
which is the correct coding for JavaScript to understand it as </script> , but without a browser interpreting it as a literal closing tag script. Some naively written JavaScript coding procedures will not convert this because the sequence does not contain the characters \ , " or ' . I just thought that I would mention some nuances of XSS prevention for other people who found this post.
If you are not sure that closing script tags is not displayed, such an attack is possible
</script><script>alert(1)</script>
which is displayed in the browser as
<script type="text/javascript"> alert('</script><script>alert(1)</script>'); </script>
and the browser interprets the script tag ending in alert('</script> , and simply executes what is in the new script tag.
Using the JavaScriptStringEncode function is safe because it displays as:
<script type="text/javascript"> alert('\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e'); </script>
which does not contain </script> for interpreting the browser.