我在数据库表中保存了安全/经过净化的HTML。
如何在Razor视图中将这个HTML内容写出?
它总是转义字符,如 <
和 ampersands 变成 &
。
我在数据库表中保存了安全/经过净化的HTML。
如何在Razor视图中将这个HTML内容写出?
它总是转义字符,如 <
和 ampersands 变成 &
。
假设您的内容存储在名为 mystring
的字符串中...
您可以使用以下代码:
@Html.Raw(mystring)
你也可以将字符串转换为 HtmlString
或其他实现了模型中的 IHtmlString
接口或直接内联使用普通的 @
:
@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString
// Say you have a bit of HTML like this in your controller:
ViewBag.Stuff = "<li>Menu</li>"
// Then you can do this in your view:
@MvcHtmlString.Create(ViewBag.Stuff)
您可以使用
@{ WriteLiteral("html string"); }
Html.Raw()
在那里无效。 - shanabus有时候使用原始的 HTML 可能会比较棘手,主要是因为 XSS 漏洞的存在。如果这是一个问题,但你仍然想使用原始的 HTML,那么你可以对危险部分进行编码。
@Html.Raw("(<b>" + Html.Encode("<script>console.log('insert')</script>" + "Hello") + "</b>)")
结果在
(<b><script>console.log('insert')</script>Hello</b>)
:
ViewData["string"] = DBstring;
@Html.Raw(ViewData["string"].ToString())
@MvcHtmlString.Create(ViewBag.Stuff)
之外,我建议您还使用AntiXSS库,正如phill所建议的那样http://haacked.com/archive/2010/04/06/using-antixss-as-the-default-encoder-for-asp-net.aspx
它可以对几乎所有可能的XSS攻击字符串进行编码。
使用RazorEngine中的模板函数的完整示例(例如用于生成电子邮件):
@model SomeModel
@{
Func<PropertyChangeInfo, object> PropInfo =
@<tr class="property">
<td>
@item.PropertyName
</td>
<td class="value">
<small class="old">@item.OldValue</small>
<small class="new">@item.CurrentValue</small>
</td>
</tr>;
}
<body>
@{ WriteLiteral(PropInfo(new PropertyChangeInfo("p1", @Model.Id, 2)).ToString()); }
</body>
@Html.Raw()
- Chris S