Add Razor runtime compilation when developing ASP.NET Core

When I started looking into ASP.NET Core, I was a bit surprised that I had to compile my web project in order to publish changes in cshtml Razor files. Runtime compilation of Razor files just worked out of the box with ASP.NET MVC. In this post, I'll show you how we solved this when migrating the elmah.io app to ASP.NET Core.

Microsoft wrote some good documentation on how to enable runtime compilation of Razor files in ASP.NET Core. You can even click a checkbox when creating a new (> ASP.NET Core 3.1) project. I like to have my main configuration in strongly-typed C# with the benefits of having IntelliSense, which isn't the case with the solution provided as part of the Wizard.

To set up runtime compilation, start by installing the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package:

Install-Package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

In the ConfigureServices method in the Startup.cs file, call the AddRazorRuntimeCompilation method. Since we only update Razor files during development and not in production (right?), wrap the call in an if statement like this:

// ...

var mvcBuilder = services.AddControllersWithViews();

if (Env.IsDevelopment())
{
    mvcBuilder.AddRazorRuntimeCompilation();
}

// ...

The IsDevelopment call ensure that runtime compilation is only added during development. The Env property should be injected in the constructor if not already there:

public IWebHostEnvironment Env { get; set; }

public Startup(IWebHostEnvironment env)
{
    Env = env;
}

An additional benefit of configuring this in C# is the possibility to include options. Like if you prefer to have Razor files in custom directories:

mvcBuilder.AddRazorRuntimeCompilation(options =>
{
    options.FileProviders.Add(new PhysicalFileProvider(customPath));
});

If you prefer having configuration like this out of C#, you should check out Microsoft's documentation and go with the launchSettings.json-based approach.