Pre-Compile Your Views in ASP.Net MVC

The default behaviour for views in ASP.Net MVC up to version 5 is that they are compiled when the first user requests them in IIS. When the view isn’t that complicated, the user only experiences a minimal delay before the web page is displayed in the browser. That is true as long as the view compiles. If not, your users will get a page like this one:

Compilation Error

The deferred compilation means that compilation errors will not pop up when you compile your code, but only when you request the page. In bigger projects that is nothing you want to do manually. While automated tests that call every single page in your application can catch those errors, there is an even better and faster way to solve this problem: compile your views whenever you build your application.

Open the *.csproj file and search for the MvcBuildViews property. All you need to do is to change the value from false to true:

Visual Studio should automatically detect the change and reload the project. Should this not work, you can manually restart Visual Studio.

If you now compile your project, it will compile your views as well and reports errors immediately:

The necessary build steps where introduced with ASP.Net MVC 3 and should therefore be present in all your current projects.

 

.Net Core

In Visual Studio 2017 the ASP.Net MVC template for .Net Core already contains the NuGet package that pre-compiles your views as part of the build process:

You can verify this by making a small change to one of the variables used in one of your views. The next rebuild should catch this error. Should this not be the case, you can add the NuGet package manually.

 

Conclusion

Pre-compilation of Views in ASP.Net MVC is easily done and should be activated in all projects. The compilation overhead is minimal, especially when you compare it how long it would take you to check each and every page in your application.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.