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

Christian Gollhardt picture Christian Gollhardt · Jun 9, 2018 · Viewed 10.7k times · Source

Yesterday I updated to net core 2.1.

Now if I am debugging, the views getting precompiled, which ofcourse takes a long time during startup... Is it possible to fall back to the previous behavior, where the Views are compiled just in time, if it is needed?

Output

I have no reference related to precompilation in my csproj. Is it something that comes from the meta package?

  <ItemGroup>
    <PackageReference Include="JetBrains.Annotations" Version="11.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.0" PrivateAssets="All" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="2.5.0" />
    <!--<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="2.0.0" PrivateAssets="All" />-->
  </ItemGroup>

Answer

Christian Gollhardt picture Christian Gollhardt · Jun 10, 2018

.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>

.net core >= 3

Microsoft created a Nuget Package. This is documented here.

Just reference Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation in your .csproj file conditionally.

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

Also configure your services

    public void ConfigureServices(IServiceCollection services)
    {
        IMvcBuilder builder = services.AddRazorPages();

#if DEBUG
            if (Env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation();
            }
#endif
    }