MvcHtmlString.ToHtmlString () does not encode HTML?

Related to this question I am playing with XSS issues in my ASP.NET MVC project, and I got confused in the MvcHtmlSTring.ToHtmlString () method. From the documentation "Returns a string encoded in HTML that represents the current object.", But in my case this does not work:

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\">"); 

MvcHtmlString output

 <SCRIPT/XSS SRC="htpp://ha.ckers.org/css.js"> 

The output of encoded <is behavior I would suspect!

 &lt;SCRIPT/XSS SRC=&quot;htpp://ha.ckers.org/css.js&quot;&gt; 

Did I miss something?

+7
source share
2 answers

MvcHtmlString (or HtmlString , or anything that implements IHtmlString ) is for strings that should be released as HTML verbatim - that is, by making it MvcHtmlString, you say that you really want HTML tags.

The difference is that you are sending a string to an ASP.NET page using <%: .. %> (new in ASP.NET 4 or later). In this case, the ASP.NET engine will automatically install the usual HtmlEncode strings (or something that does not implement IHtmlString), while the MvcHtmlString will be displayed verbatim / unencoded.

i.e. I think the documentation is incorrect. There, connect the ticket with the equivalent error in the documentation of the HtmlString constructor, which they fixed. (I thought I wrote this: // maybe mine is closed as a duplicate of someone else?) I did not notice that the MvcHtmlString documentation was incorrect.

+8
source

The MSDN documentation is correct, but maybe a little confusing. The MvcHtmlString and IHtmlString are used to represent a string that has already been encoded in HTML format. MSDN says:

Returns an HTML encoded string that represents the current object.

The object you passed to the MvcHtmlString object MvcHtmlString already been encoded in HTML, so both .ToString() and .ToHtmlString() just return the object you passed.

Please note that the MSDN docs clearly state that:

The ToHtmlString and ToString methods return the same value.

So why all this? Two reasons:

  • In the Razor view engine and in ASP.NET Web Forms v4, an object that implements IHtmlString is written as raw data. Viewers suggest that the person creating the IHtmlString has already processed the data.
  • IHtmlString has its own stringify method, so it should not have the same implementation as ToString() . While ToHtmlString() should return HTML, you can easily imagine that ToString() can return some debugging information other than the developer.
+8
source

All Articles