ASP.NET MVC 4 HtmlHelper - mix decoded HTML with encoded HTML

混江龙づ霸主 提交于 2019-12-08 02:29:41

问题


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:

&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.



来源:https://stackoverflow.com/questions/15765539/asp-net-mvc-4-htmlhelper-mix-decoded-html-with-encoded-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!