-
Notifications
You must be signed in to change notification settings - Fork 84
@Raw
rcheung9 edited this page Dec 5, 2023
·
11 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.
IRazorEngine razorEngine = new RazorEngine();
IRazorEngineCompiledTemplate template = razorEngine.Compile("Hello @Model.Name");
string result = template.Run(new
{
Name = "<b>Test</b>"
});
Console.WriteLine(result);
will output
Hello <b>Test</b>
RazorEngine razorEngine = new RazorEngine();
var razorEngineCompiledTemplate = razorEngine.Compile<HtmlSafeTemplate>(
"<div title=\"@Model.FirstName\">This is now safe: @Model.FirstName</div>\n" +
"<div>but not this: @Raw(Model.FirstName)</div>");
string result = razorEngineCompiledTemplate.Run(instance =>
{
instance.Model = new AnonymousTypeWrapper(new
{
FirstName = "<script>alert(\"1\");</script>",
LastName = "123"
});
});
Console.WriteLine(result);
Output:
<div title="<script>alert("1");</script>">This is now safe: <script>alert("1");</script></div>
<div>but not this: <script>alert("1");</script></div>
public class HtmlSafeTemplate : RazorEngineTemplateBase
{
class RawContent
{
public object Value { get; set; }
public RawContent(object value)
{
Value = value;
}
}
public object Raw(object value)
{
return new RawContent(value);
}
public override void Write(object obj = null)
{
object value = obj is RawContent rawContent
? rawContent.Value
: System.Web.HttpUtility.HtmlEncode(obj);
base.Write(value);
}
public override void WriteAttributeValue(string prefix, int prefixOffset, object value, int valueOffset, int valueLength, bool isLiteral)
{
value = value is RawContent rawContent
? rawContent.Value
: System.Web.HttpUtility.HtmlAttributeEncode(value?.ToString());
base.WriteAttributeValue(prefix, prefixOffset, value, valueOffset, valueLength, isLiteral);
}
}