How to prevent asp.net core mvc from compile cshtml view when deploying
To avoid the performance problems associated with compiling CSHTML at runtime, CSHTML files in ASP.NET Core MVC project will be compiled into DLLS by default , but sometimes the CSHTML view files are expected to be modified at runtime. Some articles online told us to add <MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish> into the csproj file, but the practice is for the old version of .NET Core, which does not work in newer versions such as.NET 5/6.
The following method is one that I have verified works in the latest version of.NET Core without compiling CSHTML views.
Step one:
Install-Package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
Step two: In Program.cs, add AddRazorRuntimeCompilation() after AddControllersWithViews() as below:
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
Step three: Modify the csproj file, add the following options into <PropertyGroup></PropertyGroup>:
<MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish> <RazorCompileOnBuild>false</RazorCompileOnBuild>
After completing the above three steps and republishing the ASP.NET Core MVC project, we can see that the CSHTML view file is not compiled into the DLL file.