.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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…