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 ...>
    ...
    <PropertyGroup>
        ...
        <MvcBuildViews>true</MvcBuildViews>
        ...

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.

Tweet about this on TwitterShare on FacebookEmail this to someoneShare on TumblrShare on LinkedIn

Tags: , , , ,

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

  1. 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.

  2. 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](http://example.com)

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

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax