Codementor Events

How to enable dynamic compilation in ASP.NET Core

Published Jan 23, 2020

In previous versions of ASP.NET MVC and Core, changes to a (cs)html page were reflected immediately (after refreshing the browser of course). However, this is not the case anymore in the newest version of the ASP.NET framework.

Thankfully, there is a pretty easy solution to this.

First of all, add the following line to your csproj file(s):

<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.0" Condition="'$(Configuration)' == 'Debug' " />

Then add the following line to Startup.cs

public IWebHostEnvironment Env { get; set; }

Now to initialize the webhost environment, we need to adapt the Startup-constructor

public Startup(IConfiguration configuration,IWebHostEnvironment env)
{
  Configuration = configuration;
  this.Env = env;
}

Now, in order to initialize dynamic compilation finally we to modify the ConfigureServices method in Startup

//other lines omitted
        IMvcBuilder builder = services.AddRazorPages();
#if DEBUG
        if (Env.IsDevelopment())
        {
            builder.AddRazorRuntimeCompilation();
        }
#endif

That is it, from now when you are developing in Visual Studio, you can save the (cs)html file, refresh your browser and see the result. It has been a real timesave for me

Discover and read more posts from Iede Snoek
get started