Using Razor Templates Beyond Web Pages and ASP.NET

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:

  1. A class library (named RazorAnywhere in this post)
  2. A console app (named RazorAnywhere.Sample in 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.

Picture of Nick Kovalenko

Nick Kovalenko

Nick is an experienced .NET software engineer with a B.S. in Software Engineering. He specializes in creating maintainable and performant code, having designed, developed, and maintained multiple complex systems throughout the entire development lifecycle. While his primary expertise lies in .NET, he is also proficient in JavaScript. Outside of his professional work, Nick enjoys hiking and playing the piano.

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.