Skip to content

Switch from RazorEngine cshtml templates

Alexander Selishchev edited this page Oct 22, 2026 · 8 revisions

Classic RazorEngine code

if (Engine.Razor.IsTemplateCached(TemplateName, typeof(BaseEmailModel)))
{
    parsedContent = Engine.Razor.Run(TemplateName, typeof(BaseEmailModel), model);
}
else
{
    var viewPath = Path.Combine(Statics.EmailTemplatesPath, $"{TemplateName}.cshtml");
    var viewContent = ReadTemplateContent(viewPath);
    parsedContent = Engine.Razor.RunCompile(viewContent, TemplateName, null, model);
}

RazorEngineCore code

private static ConcurrentDictionary<string, IRazorEngineCompiledTemplate> TemplateCache = new ConcurrentDictionary<string, IRazorEngineCompiledTemplate>();
IRazorEngineCompiledTemplate compiledTemplate = TemplateCache.GetOrAdd(TemplateName, name =>
{
   RazorEngine razorEngine = new RazorEngine();
   string viewPath = Path.Combine(Statics.EmailTemplatesPath, name + ".cshtml");
   return razorEngine.Compile(File.ReadAllText(viewPath));
});

return compiledTemplate.Run(model); 

Template

You need to remove the @model directive from the template, as RazorEngineCore controls the model. If you use a strongly typed model and would like to keep IntelliSense suggestions, put the @inherits directive on top of the template:

@inherits RazorEngineCore.RazorEngineTemplateBase<MyModel>
...

Clone this wiki locally