Search code examples
c#.netrazor.net-core

Using Razor outside of MVC in .NET Core


I would like to use Razor as a templating engine in a .NET console application that I'm writing in .NET Core.

The standalone Razor engines I've come across (RazorEngine, RazorTemplates) all require full .NET. I'm looking for a solution that works with .NET Core.


Solution

  • Recently I've created a library called RazorLight.

    It has no redundant dependencies, like ASP.NET MVC parts and can be used in console applications. For now it only supports .NET Core (NetStandard1.6) - but that's exactly what you need.

    Here is a short example:

    IRazorLightEngine engine = EngineFactory.CreatePhysical("Path-to-your-views");
    
    // Files and strong models
    string resultFromFile = engine.Parse("Test.cshtml", new Model("SomeData")); 
    
    // Strings and anonymous models
    string stringResult = engine.ParseString("Hello @Model.Name", new { Name = "John" });