How do I force Razor View Files to compile before it's too late?

  • Page Owner: Not Set
  • Last Reviewed: 2021-04-16

I'd like to precompile my razor views so that I can try to catch errors before production. How can I do that?


Answer

Update your CSProj file with 2 key commands

In Property Group section add the following lines. This will ONLY Compile views while in Release mode. It does add some time to the build process.

<MvcBuildViews Condition="'$(Configuration)'=='Debug'">false</MvcBuildViews>
<MvcBuildViews Condition="'$(Configuration)'=='Release'">true</MvcBuildViews>

This is its own element, and usually is added near the bottom. This is where the magic happens.

<Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
<AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" />
</Target>