Related to this question I play around with XSS issues in my ASP.NET MVC project and I´m confused with the MvcHtmlSTring.ToHtmlString() method. From the documentation "Returns an HTML-encoded string that represents the current object.", but it doesn´t work in my case:
var mvcHtmlString = MvcHtmlString.Create("<SCRIPT/XSS SRC=\"htpp://ha.ckers.org/css.js\">").ToHtmlString();
var encoded = HttpUtility.HtmlEncode("<SCRIPT/XSS SRC=\"htpp://ha.ckers.org/css.js\">");
Output of mvcHtmlString
<SCRIPT/XSS SRC="htpp://ha.ckers.org/css.js">
Output of encoded <-- this is the behaviour I would suspect!
<SCRIPT/XSS SRC="htpp://ha.ckers.org/css.js">
Did I miss something?
MvcHtmlString (or HtmlString, or anything that implements IHtmlString) is for strings that should be emitted as HTML verbatim - i.e. by making that an MvcHtmlString you're telling it that you actually want those HTML tags.
The difference is when you emit the string into an ASP.NET page using <%: .. %>
(new in ASP.NET 4 or later). In that case the ASP.NET engine will automatically HtmlEncode regular strings for you (or anything that doesn't implement IHtmlString) whereas the MvcHtmlString will be emitted into the page verbatim / unencoded.
i.e. I think the documentation is wrong. There's a connect ticket with the equivalent error in the HtmlString constructor documentation, which they did fix. (I thought I filed that :-/ maybe mine got closed as a duplicate of someone else's?) I didn't notice the MvcHtmlString documentation was wrong too.
The MSDN documentation is correct, but perhaps a bit confusing. The MvcHtmlString
and IHtmlString
interface are used to represent a string that has already been HTML encoded. MSDN says:
Returns an HTML-encoded string that represents the current object.
The object you passed in to the MvcHtmlString
object was already HTML-encoded, so both .ToString()
and .ToHtmlString()
merely return the object you passed in.
Please note that the MSDN docs do clearly state that:
The ToHtmlString and ToString methods return the same value.
So why have all this? Two reasons:
IHtmlString
is written out as raw data. The view engines assume that the person creating the IHtmlString
has already sanitized the data.IHtmlString
has its own stringify method so that it need not have the same implementation as ToString()
. While ToHtmlString()
must return the HTML, you could easily imagine that ToString()
might return some developer-friendly debug information.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With