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.

Add Razor runtime compilation when developing 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.

elmah.io: Error logging and Uptime Monitoring for your web apps

This blog post is brought to you by elmah.io. elmah.io is error logging, uptime monitoring, deployment tracking, and service heartbeats for your .NET and JavaScript applications. Stop relying on your users to notify you when something is wrong or dig through hundreds of megabytes of log files spread across servers. With elmah.io, we store all of your log messages, notify you through popular channels like email, Slack, and Microsoft Teams, and help you fix errors fast.

See how we can help you monitor your website for crashes Monitor your website