问题
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?
回答1:
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:
<script>alert("hello");</script>
was getting decoded to "plain text" html, which I wanted, but then MvcHtmlString.Create was decoding it again and it got rendered as HTML.
来源:https://stackoverflow.com/questions/15765539/asp-net-mvc-4-htmlhelper-mix-decoded-html-with-encoded-html