How do I output raw html when using RazorEngine (N

2019-02-01 02:49发布

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:

Razor.Parse(template, model);

on the following Razor template:

<!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?

6条回答
Root(大扎)
2楼-- · 2019-02-01 03:31

FYI I have a fork that includes the @Html.Raw(...) syntax here:

https://github.com/Antaris/RazorEngine/pull/105

查看更多
女痞
3楼-- · 2019-02-01 03:32

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 HtmlEncodedString and RawString.

To use the latter, simply make a call to the inbuilt Raw method of TemplateBase:

@Raw(Model.EmailContent)
查看更多
男人必须洒脱
4楼-- · 2019-02-01 03:33

If you have a custom base class for your templates, you can code Write method to behave similar to normal MVC template: if the output value is IHtmlString it should not encode it.

Here's the code I'm using in my TemplateBase class:

// 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);
}
查看更多
别忘想泡老子
5楼-- · 2019-02-01 03:33

I found all of these worked with me.

@{var myHtmlString = new HtmlString(res);}
@myHtmlString


  @MvcHtmlString.Create(res)

  @Html.Raw(res)
查看更多
疯言疯语
6楼-- · 2019-02-01 03:40

Built a wrapper for RazorEngine that adds in support for @Html.Raw() and @Html.Partial()

https://github.com/b9chris/RazorEngineComplete

查看更多
我只想做你的唯一
7楼-- · 2019-02-01 03:46

I am using RazorEngine 3.8.2 and @Raw(Model.Content) is working perfectly fine for me.

查看更多
登录 后发表回答