C# 使用 RazorEngine 时如何输出原始 html(不是来自 MVC)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9661180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I output raw html when using RazorEngine (NOT from MVC)
提问by KallDrexx
I am trying to generate emails with HTML content. this content has already gone through sanitation so I am not worried in that regard, however when I call:
我正在尝试生成带有 HTML 内容的电子邮件。此内容已经经过卫生处理,因此我对此并不担心,但是当我致电时:
Razor.Parse(template, model);
on the following Razor template:
在以下 Razor 模板上:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<body>
@(new System.Web.HtmlString(Model.EmailContent))
</body>
</html>
the email that is outputted is HTMl encoded, but I need it decoded. How can I accomplish this?
输出的电子邮件是 HTMl 编码的,但我需要对其进行解码。我怎样才能做到这一点?
采纳答案by Matthew Abbott
RazorEngine, like MVC's Razor View Engine, will automatically encode values written to the template. To get around this, we've introduce an interface called IEncodedString, with the default implementations being HtmlEncodedStringand RawString.
RazorEngine 与 MVC 的 Razor View Engine 一样,会自动编码写入模板的值。为了解决这个问题,我们引入了一个名为 的接口IEncodedString,默认实现是HtmlEncodedString和RawString。
To use the latter, simply make a call to the inbuilt Rawmethod of TemplateBase:
要使用后者,只需调用 的内置Raw方法TemplateBase:
@Raw(Model.EmailContent)
回答by Tod Thomson
FYI I have a fork that includes the @Html.Raw(...) syntax here:
仅供参考,我有一个包含 @Html.Raw(...) 语法的叉子:
回答by Iravanchi
If you have a custom base class for your templates, you can code Writemethod to behave similar to normal MVC template: if the output value is IHtmlStringit should not encode it.
如果您的模板有自定义基类,您可以编写Write方法使其行为类似于普通 MVC 模板:如果输出值为 ,IHtmlString则不应对其进行编码。
Here's the code I'm using in my TemplateBaseclass:
这是我在TemplateBase课堂上使用的代码:
// Writes the results of expressions like: "@foo.Bar"
public virtual void Write(object value)
{
if (value is IHtmlString)
WriteLiteral(value);
else
WriteLiteral(AntiXssEncoder.HtmlEncode(value.ToString(), false));
}
// Writes literals like markup: "<p>Foo</p>"
public virtual void WriteLiteral(object value)
{
Buffer.Append(value);
}
回答by MuniR
I found all of these worked with me.
我发现所有这些都对我有用。
@{var myHtmlString = new HtmlString(res);}
@myHtmlString
@MvcHtmlString.Create(res)
@Html.Raw(res)
回答by curious.netter
I am using RazorEngine 3.8.2 and @Raw(Model.Content)is working perfectly fine for me.
我正在使用 RazorEngine 3.8.2 并且@Raw(Model.Content)对我来说工作得很好。
回答by Chris Moschini
Built a wrapper for RazorEngine that adds in support for @Html.Raw()and @Html.Partial()
为 RazorEngine 构建了一个包装器,增加了对@Html.Raw()和@Html.Partial()

