How to disable precompiled views in net core 2.1+ / net 5 for debugging?

.net core >= 3 (also called .net 5)

Microsoft created a Nuget Package. This is documented here.

Just reference Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation in your .csproj file conditionally. Don't forget to adjust the version, you actualy use.

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

Also configure your services

    public void ConfigureServices(IServiceCollection services)
    {
        // your MVC Builder (AddRazorPages/AddControllersWithViews)
        IMvcBuilder builder = services.AddRazorPages();

#if DEBUG
            // Only use Runtime Compilation on Debug
            if (Env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation();
            }
#endif
    }

Ofcourse, when you want to general use Runtime Compilation, even when published, you don't need all the conditions.

.net core >= 2.1 && < 3

This can be accomplished using the property RazorCompileOnBuild in the .csproj file:

<PropertyGroup>
  <TargetFramework>netcoreapp2.1</TargetFramework>
  <RazorCompileOnBuild>false</RazorCompileOnBuild>
  <RazorCompileOnPublish>true</RazorCompileOnPublish>
</PropertyGroup>

This way the Razor files are only precompiled during publishing.

Depending on the usecase you also want to configure this depending on the build configuration:

<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
  <RazorCompileOnBuild>false</RazorCompileOnBuild>
  <RazorCompileOnPublish>true</RazorCompileOnPublish>
</PropertyGroup>

You should set MvcRazorCompileOnPublish to false, with this, it will turn off all functions of view compilation that are enabled as part of publishing.

<PropertyGroup>
  <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>
</PropertyGroup>