Tech Tip: Enabling Razor files to be editable during Runtime in a Single Executable File

Updated on: 10 Jul 2020

In .Net Framework, razor files (.cshtml files) in MVC projects are editable during runtime by default. In the default .Net core web application projects, razor files are compiled and cannot be updated during runtime.

You can change this behavior with the following steps:

1. Installing the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package via Nuget.

2. Adding the code services.AddControllersWithViews().AddRazorRuntimeCompilation() for Controller Views or adding the code services.AddRazorPages().AddRazorRuntimeCompilation() for razor pages in the ConfigureServices(IServiceCollection services) in the Startup.cs file.

But  if you compile your .Net Core web application project into a single executable file, you will notice that your views are compiled into the single executable file  as well despite doing the above steps.

To resolve the issue, you will need to add the following xml snippets into your .csproj file:

For MVC Views:

<ItemGroup>
    <ViewFiles Include="$(ProjectDir)\Views\**\*.cshtml" />
  </ItemGroup>
  <Target Name="CopyViewFilesAfterPublish" AfterTargets="Publish">
    <Copy SourceFiles="@(ViewFiles)" DestinationFolder="$(PublishDir)\Views\%(RecursiveDir)" />
  </Target>
.csproj

For Razor Pages:

<ItemGroup>
    <ViewFiles Include="$(ProjectDir)\Pages\**\*.cshtml" />
  </ItemGroup>
  <Target Name="CopyViewFilesAfterPublish" AfterTargets="Publish">
    <Copy SourceFiles="@(ViewFiles)" DestinationFolder="$(PublishDir)\Pages\%(RecursiveDir)" />
  </Target>
.csproj

Here are some more posts