I am trying to get Razor runtime compilation working in an MVC Core 3.1 web application for Razor pages, but it's not working for me. It's frustrating as I have several previous MVC Core web applications across several releases (2.0, 2.1, 3.1) using controllers and views that work as expected.
When publishing the project, I am expecting to see a /pages folder in the publish output with my .cshtml files. There isn't one, and there are no .cshtml files anywhere in the publish folder.
The website works just fine, serving pages as expected, so the pages are compiled into the WebApplication3.1.Views.dll
assembly correctly. No issues here.
To reproduce, I created a new MVC project with Razor runtime compiliation enabled at creation, following the instructions in https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-compilation?view=aspnetcore-3.1&tabs=visual-studio. I can confirm the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.dll
assembly is present in the published output, and services.AddRazorPages().AddRazorRuntimeCompilation()
is called from the Startup.ConfigureServices
method. Having looked at the docs, and several StackExchange answers, this should be enough to enable runtime compilation. the .csproj file looks like this:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>WebApplication3._1</RootNamespace>
<CopyRefAssembliesToPublishDirectory>false</CopyRefAssembliesToPublishDirectory>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.4" />
</ItemGroup>
</Project>
I then added <Target>
elements to the .csproj file to get the pages in to the publish folder, which worked, but when I deployed and changed a .cshtml file I then got an exception that the Microsoft.AspNetCore.Antiforgery.dll
couldn't be found. So I can see that runtime compilation kind of works, but is broken.
At this point this seems to be more complicated than it should be, considering that in other MVC Core 3.1 controller/view based projects of mine it just worked. Am I missing something really obvious?
I have also looked at other StackExchange questions, this one in particular, but it says essentially the same thing:
.NET Core 3.0: Razor views don't automatically recompile on change
I am using Visual Studio 2019 Professional version 16.6.4
It looks like you need the RazorCompileOnPublish
property, which you can set in your .csproj file:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<RazorCompileOnPublish>false</RazorCompileOnPublish>
...
</PropertyGroup>
...
</Project>
Setting RazorCompileOnPublish
to false
should be all that's needed, but I suspect you don't need that CopyRefAssembliesToPublishDirectory
property in your .csproj.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With