Razor is a powerful tool that combines templates with data model to produce resulting text. Originally released in 2011, it has since evolved significantly, and now it is de-facto Microsoft recommended template engine.
While it is standard practice to use Razor for web apps such as ASP.NET Core MVC or Blazor, it is rarely employed for other purposes. In this blog post, we will discuss the reasons for this, why Razor could be a good fit as a general-purpose template engine, as well as develop a small standalone library that allows you to use Razor in any app.
Use Cases
One nice thing about Razor is that is does not really care about the kind of output it produces. Yes, that’s right – even though it was originally released as part of the MVC toolkit, aimed at web pages – it is not strictly tied to HTML or any other syntax and does not enforce any rules on what the generated text should look like.
Thanks to this, Razor is very flexible and could be used to generate lots of different things:
- HTML pages
- Emails
- Code
- Documentation
- Plain text
- Just about anything else!
That said, it is clear that Razor is primarily used in web apps to generate HTML, and this is reflected in its syntax, tooling, and libraries. We will see multiple examples of this throughout the blog post.
Razor Beyond ASP.NET
While it is absolutely possible to use Razor outside ASP.NET web apps, there is some coupling, and it complicates the setup process compared to other 3rd party template engines like Scriban or Handlebars.NET. Except for that, Razor is an excellent choice when it comes to template engines in .NET: it is fast (templates are compiled at build time), has many features, allows to embed C# code into pages, and has decent IDE support (including IntelliSense).
This blog post aims to explain how to set up a fresh project to use Razor, and possibly extract this logic into a separate library to keep things clean.
Note: This blog post specifically targets Razor Pages (*.cshtml files), not Razor Components (*.razor files). It is technically possible to achieve the same behavior with Razor Components too, however that’s a completely different system. I may cover that topic in more detail in the future.
Final code is available on GitHub.
Creating the Projects
First we will create and configure projects that will be used in this sample. The solution consists of two projects:
- A class library (named
RazorAnywherein this post) - A console app (named
RazorAnywhere.Samplein this post)
Class Library
The purpose of the library is to abstract away Razor setup code and expose a friendly API to the console app. Once the empty class library is created, we will add a package reference to Microsoft.AspNetCore.Mvc (can be done via NuGet):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
</ItemGroup>
</Project>
This package provides, in particular, types such as RazorPage that we will use, as well as several other types that are used by the generated Razor code. That said, it obviously contains many more types that we won’t ever need (unless this is a web app), so we can ignore them.
Note: It is technically possible to setup Razor and achieve the same behavior without referencing Microsoft.AspNetCore.Mvc, but the library will then need to define all missing compiler required types, and the logic for compiler required methods contained in the Razor page (what would normally be contained in RazorPage class). We will stick to using Microsoft.AspNetCore.Mvc for simplicity.
Console App
The console app will define a template, render it to string, and output to console. It will reference and use the class library. Once the empty app is created, we will need to do several things with the *.csproj file:
- Reference the class library
- Set the project SDK to
Microsoft.NET.Sdk.Razor - Set MSBuild properties:
AddRazorSupportForMvc,RazorLangVersion
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AddRazorSupportForMvc>true</AddRazorSupportForMvc>
<RazorLangVersion>latest</RazorLangVersion>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RazorAnywhere\RazorAnywhere.csproj" />
</ItemGroup>
</Project>
Note: Microsoft.NET.Sdk.Razor is available starting from .NET SDK 6.0.
The Razor SDK is used to parse and compile Razor templates, and also defines several properties that configure the compilation process. AddRazorSupportForMvc configures the SDK to enable the compilation of templates, while RazorLangVersion specifies the Razor version to use.
Note: Since Razor templates compile to C# source files on build using a source generator, it can be very useful to dump those files to disk and check the generated code (for debugging, or just curiosity). For that you can set the EmitCompilerGeneratedFiles property to true in the console app project file: <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
Implementing the API
Now that the projects are set up it is time to write the API that the class library will expose. Ultimately this means that we need to design and implement a system on top of the existing Razor APIs to allow Razor Pages to be rendered to string, and make as simple as possible.
Please note that while this post describes one of the possible solutions, it is entirely up to you to design the API. So feel free to adjust to your own needs and preferences if you want to implement it yourself.
We will take advantage of the @inherits directive in Razor: it allows to specify a custom base type that the generated page class will inherit from. That type will implement a custom interface that exposes the ability to render the page to string.
Let’s define the IRazorPage interface:
namespace RazorAnywhere;
public interface IRazorPage
{
Task<string> RenderAsync();
}
While it is not necessary to define the interface (could specify the method in base class directly), it enables polymorphic behavior where we don’t know the type of the model and can’t use generic base type. This could be useful when, for example, all pages are collected and created using reflection, and then cast to IRazorPage and rendered.
Next step is to define the custom RazorPage<TModel> class that all pages will inherit from:
using System.Text;
using System.Text.Encodings.Web;
namespace RazorAnywhere;
public abstract class RazorPage<TModel> : Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>, IRazorPage
{
private readonly MemoryStream _output = new();
public new required TModel Model { get; set; }
protected RazorPage()
{
HtmlEncoder = HtmlEncoder.Default;
ViewContext = new()
{
Writer = new StreamWriter(_output)
};
}
public async Task<string> RenderAsync()
{
await ExecuteAsync();
await Output.FlushAsync();
_output.Seek(0, SeekOrigin.Begin);
string text = Encoding.UTF8.GetString(_output.ToArray());
return text;
}
}
To render pages to string, we will simply use MemoryStream (then passed to ViewContext.Writer, which is where the output is written), and then convert its content to string using the Encoding class.
We also had to redefine the Model property because base class computes it from ViewData which we don’t use.
Adding Compiler Required Types
Before we move on to the console app, there is one more thing we need to do: add types that are required by the compiler when compiling Razor Pages.
While most of the types are already present from Microsoft.AspNetCore.Mvc package, there is still one type that we need to add manually to make the compiler happy, which is ApplicationPartAttribute.cs. Feel free to copy the source code over from the link and paste it in the library (make sure namespaces are kept).
We should now be good to go and start adding Razor Pages to the console app.
Adding a Razor Page
Let’s test if we can render pages to string by adding a simple Razor Page (and backing C# file) to the console app. I will name it TestPage.cshtml:
@using RazorAnywhere
@namespace RazorAnywhere.Sample
@inherits RazorPage<TestPageModel>
Hello from Razor!
Here is a list of people who love @Model.Snack:
@foreach(var (name, age) in Model.People)
{
@:@name, who is @age y.o.
}
And the model:
namespace RazorAnywhere.Sample;
public class TestPageModel
{
public string Snack { get; set; }
public (string Name, int Age)[] People { get; set; }
}
Now, in Program.cs, we can finally assemble all pieces together and output the rendered string:
using RazorAnywhere;
using RazorAnywhere.Sample;
TestPageModel model = new()
{
Snack = "Doritos",
People = [("John", 42), ("J.", 41), ("Nick", 40)]
};
IRazorPage page = new TestPage()
{
Model = model
};
string text = await page.RenderAsync();
Console.WriteLine(text);
Which gives us:
Hello from Razor!
Here is a list of people who love Doritos:
John, who is 42 y.o.
J., who is 41 y.o.
Nick, who is 40 y.o.
So, we managed to define a custom Razor Page and render it to string!
Conclusion
In this blog post, we took a look at how to use Razor Pages with any app, and implemented a very small library that allows us to render those pages to string. This is by no means the end of the road, and there are many more features that could be added, for example page nesting, or auto-collection of all Razor Pages and rendering them knowing only the type of the model.
If you are a .NET developer who is faced with a problem like email generation, docs generation, or any other kind of task that template engines can solve, definitely try Razor!
Also, feel free to check the code on GitHub and/or contribute.


