Pre-Compiling your MVC Views

One part of MVC Views that can cause problems is that the cshtml can cause run-time errors. This can lead to bugs in Production or found by QA that could be avoided if it was built when you build the project. Pre-compiling can be turned on to avoid those problems. You add this in the project file of your web application, by setting the true in the .csproj. See http://www.dotnetcurry.com/ShowArticle.aspx?ID=698 for more details.

Another reason to pre-compile views is to avoid the initial hit of compiling when the website is first hit after publishing. It also ensures that changes can’t be made on the server. I did this in ASP.Net Web Forms using the Web Deploy Project back in the day. (more information) The doesn’t create place holders on deployment as I first expected. A co-worker pointed out that we could use the aspNet compiler in a post build or in a command-line.

.\aspnet_compiler.exe -v / -p C:\testdeploy c:\testdeploy2

Then we found the option in the web project’s publish Settings in Visual Studio 2012 (I have Premium).

publish

After deployment, the views are just place holders. Opening it up in notepad they say “This is a marker file generated by the precompilation tool, and should not be deleted!”. You’ll also see many .compiled files in the bin directory. For example: _contactinfo.cshtml.c4daf601.compiled

Another reference:  http://haacked.com/archive/2011/05/09/compiling-mvc-views-in-a-build-environment.aspx

Update:  do this in a VSTS build: https://stackoverflow.com/questions/37193420/precompile-asp-net-mvc-views-on-azure-web-app

There are good and similar answers on Stack Overflow: https://stackoverflow.com/questions/383192/compile-views-in-asp-net-mvc

This article is part of the GWB Archives. Original Author: Aligned

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.