Skip to content
Alexander Selishchev edited this page Jan 17, 2026 · 12 revisions

By default, RazorEngine will not encode values to be HTML safe, there are reasons for that.

  • you need to escape values by yourself
  • you need to implement @Raw helper by yourself

But dont worry, this page is here to help.

Default behavior

IRazorEnginerazorEngine=newRazorEngine();IRazorEngineCompiledTemplatetemplate=razorEngine.Compile("Hello @Model.Name");stringresult=template.Run(new{Name="<b>Test</b>"});Console.WriteLine(result);

will output

Hello <b>Test</b>

HtmlSafeTemplate

RazorEnginerazorEngine=newRazorEngine();varrazorEngineCompiledTemplate=razorEngine.Compile<HtmlSafeTemplate>("<div title=\"@Model.FirstName\">This is now safe: @Model.FirstName</div>\n"+"<div>but not this: @Raw(Model.FirstName)</div>");stringresult=razorEngineCompiledTemplate.Run(instance =>{instance.Model=newAnonymousTypeWrapper(new{FirstName="<script>alert(\"1\");</script>",LastName="123"});});Console.WriteLine(result);

Output:

<div title="&lt;script>alert(&quot;1&quot;);&lt;/script>">This is now safe: &lt;script&gt;alert(&quot;1&quot;);&lt;/script&gt;</div>
<div>but not this: <script>alert("1");</script></div>

Code NET5+

publicclassHtmlSafeTemplate:RazorEngineTemplateBase{classRawContent{publicobjectValue{get;set;}publicRawContent(objectvalue){Value=value;}}publicobjectRaw(objectvalue){returnnewRawContent(value);}publicoverridevoidWrite(objectobj=null){objectvalue=objisRawContentrawContent?rawContent.Value:System.Text.Encodings.Web.HtmlEncoder.Default.Encode(obj?.ToString()??string.Empty);base.Write(value);}publicoverridevoidWriteAttributeValue(stringprefix,intprefixOffset,objectvalue,intvalueOffset,intvalueLength,boolisLiteral){value=valueisRawContentrawContent?rawContent.Value:System.Text.Encodings.Web.HtmlEncoder.Default.Encode(value?.ToString()??string.Empty);base.WriteAttributeValue(prefix,prefixOffset,value,valueOffset,valueLength,isLiteral);}}

Code NET4.7.2

publicclassHtmlSafeTemplate:RazorEngineTemplateBase{classRawContent{publicobjectValue{get;set;}publicRawContent(objectvalue){Value=value;}}publicobjectRaw(objectvalue){returnnewRawContent(value);}publicoverridevoidWrite(objectobj=null){objectvalue=objisRawContentrawContent?rawContent.Value:System.Web.HttpUtility.HtmlEncode(obj);base.Write(value);}publicoverridevoidWriteAttributeValue(stringprefix,intprefixOffset,objectvalue,intvalueOffset,intvalueLength,boolisLiteral){value=valueisRawContentrawContent?rawContent.Value:System.Web.HttpUtility.HtmlAttributeEncode(value?.ToString());base.WriteAttributeValue(prefix,prefixOffset,value,valueOffset,valueLength,isLiteral);}}

Clone this wiki locally