How do I compile Razor Views in .NET Core (CSProj)?

In .NET Core (project.json SDK Tooling), compiling Razor views was rather simple. Add this to your project.json:

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.1.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Mvc": "1.1.0-preview1-final",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.1.0-preview4-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.Design": {
      "version": "1.1.0-preview4-final",
      "type": "build"
    }
  },
  "tools": {
    "Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.Tools": {
      "version": "1.1.0-preview4-final"
    }
  }
}

And add this to the postpublish section:

"dotnet razor-precompile --configuration %publish:Configuration% --framework %publish:TargetFramework% --output-path %publish:OutputPath% %publish:ProjectPath%",

And it was done.

But with the CSProj version of .NET Core, they didn’t go back to the old CSProj method of doing that (would that have been too simple?) rather Microsoft introduced a new way to compile razor views.

To add RAzor compilation to .NET Core (CSProj edition), there are two things that need to be added:

  1. DotNetCliToolReference for a specific version of the CodeGeneration Tools.
  2. A new PropertyGroup containing the flag needed to compile Razor Views

For DotNetCliToolReference in .csproj:

  
    <ItemGroup>
      <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
    </ItemGroup>
  

And the Compile flag later:

  <PropertyGroup>
    <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
  </PropertyGroup>

And with that, each publish should include a compilation of razor views in the output.

I’ve found shockingly little in documentation for .NET Core Tooling (CSProj); but I did find this information from an issue linked to the aspnet/templates project on Github.

A note about the CodeGeneration tools; even though 1.0.0.0 is a later version than msbuild3-final; I tried 1.0.0.0 and it didn’t work; but the msbuild3-final did. I spent enough time monkeying with this that trying to reproduce it to submit a bug report seems like wasted time. I’m going to call it a victory and say “just use msbuild3-final.” Cargo-culty? Probably; but I’ve spent too much time getting .NET Core tooling to work to try to spend more time reproducing the issues.

Advertisements