How to prevent escaping html in Razor (standalone)

2020-04-01 23:18发布

问题:

I have a Model with property Content which contains HTML string.

var model = new { Content = ... }
Razor.Parse(templateBody, model)

How can I render this string using standalone Razor.

I tried:

@(new HtmlString(Model.Content))

and also

@(HttpUtility.HtmlDecode(Model.Content))

Model.Content renders always HTML-escaped.

回答1:

In RazorEngine library special "do-not-escape-me" type is RazorEngine.Text.IEncodedString. Use simple helper method on template base class:

 @Raw("<script>alert('!');</script>")

To convince VS and Resharper to give you IntelliSense add following line at the top of template:

@inherits RazorEngine.Templating.TemplateBase


回答2:

this should work Html.Raw(Model.Content)