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.
Here is a sample code that only depends on Razor (for parsing and C# code generation) and Roslyn (for C# code compilation, but you could use the old CodeDom as well).
There is no MVC in that piece of code, so, no View, no .cshtml files, no Controller, just Razor source parsing and compiled runtime execution. There is still the notion of Model though.
You will only need to add following nuget packages:
Microsoft.AspNetCore.Razor.Language
(v2.1.1),Microsoft.AspNetCore.Razor.Runtime
(v2.1.1) andMicrosoft.CodeAnalysis.CSharp
(v2.8.2) nugets.This C# source code is compatible with NETCore, NETStandard 2 and .NET Framework. To test it just create a .NET framework or .NET core console app, paste it, and add the nugets.
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:
Here is a class to get Nate's answer working as a scoped service in an ASP.NET Core 2.0 project.
In Startup.cs
In a controller
There's a working example for .NET Core 1.0 at aspnet/Entropy/samples/Mvc.RenderViewToString. Since this might change or go away, I'll detail the approach I'm using in my own applications here.
Tl;dr - Razor works really well outside of MVC! This approach can handle more complex rendering scenarios like partial views and injecting objects into views as well, although I'll just demonstrate a simple example below.
The core service looks like this:
RazorViewToStringRenderer.cs
A simple test console app just needs to initialize the service (and some supporting services), and call it:
Program.cs
This assumes that you have a view model class:
EmailViewModel.cs
And layout and view files:
Views/_Layout.cshtml
Views/EmailTemplate.cshtml