2

I'm writing a helper method that will generate comment's HTML on a page and I want to be able to show a comment with "< script >alert("hello");< /script >" as it's content.

When using

@HttpUtility.HtmlDecode(comment.Content)

in a *.cshtml file, that script gets rendered as plain text.

But when using this HTML helper in a View:

@Html.PendingComment(comment)

the script gets rendered as HTML and gets executed:

public static IHtmlString PendingComment(this HtmlHelper helper, VoidCommentPending comment)
    {
        var sb = new StringBuilder();
        sb.Append("<p>" + HttpUtility.HtmlDecode(comment.Content) + "</p>");
        return MvcHtmlString.Create(sb.ToString());
    }

Tried with "new HtmlString()", same result, and when I changed return result from IHtmlString to string, even paragraph tags got rendered as plain text.

Is it possible to mix encoding and decoding HTML strings in HtmlHelper or should I use a different approach?

0

1 Answer 1

4

Okay, so before storing comments into database, I use HttpUtility.Encode:

model.Content= HttpUtility.HtmlEncode(model.Content);

Then I just removed decoding from my helper method

sb.Append("<p>" + comment.Content + "</p>");

and it shows "< script >alert("hello");< /script >" as plain text on my page. Problem solved.

Esentially I was "double decoding". With HttpUtility.HtmlDecode this content:

&lt;script&gt;alert(&quot;hello&quot;);&lt;/script&gt;

was getting decoded to "plain text" html, which I wanted, but then MvcHtmlString.Create was decoding it again and it got rendered as HTML.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.