ASP.NET MVC 4 HtmlHelper-将解码的HTML与编码的HTML混合在一起 [英] ASP.NET MVC 4 HtmlHelper - mix decoded HTML with encoded HTML

查看:88
本文介绍了ASP.NET MVC 4 HtmlHelper-将解码的HTML与编码的HTML混合在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个帮助程序方法,该方法将在页面上生成评论的HTML,我希望能够显示内容为< script> alert(" hello);</script>"的评论

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.

使用时

@HttpUtility.HtmlDecode(comment.Content)

在* .cshtml文件中,该脚本被呈现为纯文本.

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

但是在视图中使用此HTML帮助程序时:

But when using this HTML helper in a View:

@Html.PendingComment(comment)

脚本被渲染为HTML并被执行:

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());
    }

尝试使用"new HtmlString()",结果相同,当我将返回结果从IHtmlString更改为字符串时,甚至段落标签也被呈现为纯文本.

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

是否可以在HtmlHelper中混合使用编码和解码HTML字符串,还是应该使用其他方法?

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

推荐答案

好的,因此在将注释存储到数据库之前,我使用HttpUtility.Encode:

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

,它在我的页面上以纯文本形式显示< script> alert("hello");</script>. 问题解决了.

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

基本上我是在双重解码".使用HttpUtility.Html解码此内容:

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

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

被解码为纯文本" html,我想要的 ,然后MvcHtmlString.Create再次对其进行解码,它得到了呈现为HTML.

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

这篇关于ASP.NET MVC 4 HtmlHelper-将解码的HTML与编码的HTML混合在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆