Nomenclature
This question is about three related subjects that allow the developer to introduce code changes in a running application without having to rebuild and restart said application:
- Edit and Continue: Visual Studio's functionality to modify assemblies that are being debugged. You can edit managed code while on a breakpoint (within some constraints), and it'll magically be applied to the debuggee.
- Hot Reload: introduced with Visual Studio 2022, kind of like Edit and Continue, enabling runtime recompilation of managed code without having to be paused on a breakpoint or even having a debugger running to begin with.
- Razor Runtime Compilation: editing Razor views of a running application, by recompiling them on save of a .cshtml file.
Setup
- Visual Studio 2022 (17.4.4)
- .NET 7 (SDK: 7.0.102) or 6 (SDK: 6.0.403)
- NuGet: Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
The problems described below also occur on combinations of earlier versions of those components. Then:
Start Visual Studio 2022
Create an ASP.NET Core Web App running on .NET 6 or 7
Add the NuGet package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
Change the generated Program.cs code to the following to add Razor Runtime Compilation:
// Add services to the container. var mvcBuilder = builder.Services.AddRazorPages(); #if DEBUG mvcBuilder.AddRazorRuntimeCompilation(); #endif
Reproduction
Now set a breakpoint in any view, Index.cshtml
would be fine, and run the application.
As soon as the breakpoint is hit, change some Razor code. Or don't, the issues trigger from just having (multiple?) .cshtml files open as well.
Then hit Ctrl+S and F5 to apply your changes and continue running your application, and tada.wav:
Hot Reload can't automatically apply your changes. The app needs to be rebuilt to apply updates.
Alternatively, change some code in the code behind (.cshtml.cs). Now you will get random NullReferenceExceptions or ExecutionEngineExceptions when continuing.
Workaround
Close all .cshtml files before starting a debug session.
Questions
Is it possible to:
- Get some confirmation that I'm not the only one that encounters this?
- Have "Edit and Continue" without "Hot reload"? The settings for those seem to have been combined, it's either all or nothing.
- Make this (editing Razor files and C# code while debugging) work without getting these dreaded errors?
- How can I get Microsoft to set the Cancel key (Esc) to the Continue Editing button?