Thursday, February 11, 2016

ASP.NET MVC–Precompile Razor views on Release build

Last week I was investigating slow startup times of an ASP.NET MVC web application. We were able to trace the root cause to a really complex Razor page. This was the first page that was loaded and takes a long time to compile.

By default Razor compilation happens the first time a Razor page is requested by the browser. However you can change this and prebuild all the Razor pages by adding the MvcBuildViews tag to your .csproj file:

<?xml version="1.0" encoding="utf-8"?>
<Project>
    <PropertyGroup>
        <MvcBuildViews>true</MvcBuildViews>
        

Unfortunately it had a large impact on the build times making debugging a pain for the developers. So in the end we decided to only precompile Razor on a release build. Therefore we had to add 2 MvcBuildViews tags with a condition:

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

2 comments:

Anonymous said...

https://github.com/RazorGenerator/RazorGenerator is a better choice. It creates a .cs file per each .cshtml file and these files won't be compiled from scratch every time with each build.

Smith Cole said...

Hi, Nice update. I have a little bit idea about Asp.net Mvc when I hosted my website on Myasp.net.But this blog helps in how to slow down the startup times of an ASP.NET MVC web application. Thanks for sharing and keep blogging new updates like this.