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

I am trying to create emails with HTML content. this content has already passed sanitation, so I'm not worried about this, 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 output message is encoded by HTMl, but I need to decode it. How can i do this?

+83
c # html-encode razor
Mar 12 2018-12-12T00:
source share
4 answers

RazorEngine, like the MVC Razor View Engine, automatically encodes the values ​​written to the template. To get around this, we introduced an interface called IEncodedString , with the default implementations being HtmlEncodedString and RawString .

To use the latter, simply make a call to the built-in Raw TemplateBase method:

 @Raw(Model.EmailContent) 
+148
Mar 12 2018-12-12T00:
source share

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

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

+9
May 14 '13 at 1:47
source share

If you have your own base class for your templates, you can encode the Write method to behave just like regular MVC templates: if the output value is IHtmlString , it should not encode it.

Here is the code I use in the 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); } 
+2
Nov 12 '13 at
source share

I found that all of this worked with me.

 @{var myHtmlString = new HtmlString(res);} @myHtmlString @MvcHtmlString.Create(res) @Html.Raw(res) 
0
Jul 28 '16 at 2:42 on
source share



All Articles