How do I output raw html when using RazorEngine (NOT from MVC)

天涯浪子 提交于 2019-11-29 23:25:26

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)

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

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

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

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

I found all of these worked with me.

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


  @MvcHtmlString.Create(res)

  @Html.Raw(res)

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

https://github.com/b9chris/RazorEngineComplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!