Precompile ASP.NET MVC Razor views in Release mode to find errors at compile time

A problem we often face when developing ASP.NET MVC applications is that errors in Razor views are only detected at runtime while browsing the site. This is because the Razor views are not compiled until they are requested by the browser.

To avoid this problem, you can prebuild the views by adding the MvcBuildViews tag to your .csproj file:

<?xml version="1.0" encoding="utf-8"?>
<Project ...>

There are two problems with this approach:

  • The build process takes much longer
  • You cannot change the views when debugging the running application

To avoid these problems and still be able to find view errors, I recommend to enable Razor view compilation only for Release builds. To do so, just add two the following conditional MvcBuildViews tags:

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

You can also use the Razor view compiler externally, read more in this blog.

Tags: , , , ,

4 responses to “Precompile ASP.NET MVC Razor views in Release mode to find errors at compile time”

  1. Valentin says:

    In case there are other people perplexed by the presence in .csproj of the <AspNetCompiler…> element (in addition to MvcBuildViews) this is actually fine. It is required to be there. See

  2. ontimesheet says:

    Hi, nice article

    I think you need to uncomment the target to copy configuration as well.
    If you have an EDMX file this will break the build, can you help address that as well.

  3. Marcello says:

    Good good good!

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see

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