Is it possible to change .cshtml View and see the changes instantly using .NET Core? - asp.net-core

Context
In my .NET Framework 4.x ASP.NET MVC projects, when using the Visual Studio IDE, it was possible to edit a .cshtml view, save, then press ctrl+F5 in the browser and see the change immediately.
This seems to be no longer work in ASP.NET Core applications (using Visual Studio 2019 and .NET Core 3 Preview 5).
Question
Is this feature missing in ASP.NET Core? Is this a preview issue? Or am I missing something?

This is something that is no longer enabled by default as of ASP.NET Core 3, but it can be re-enabled as documented here:
Runtime compilation is enabled using the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package. To enable runtime compilation, apps must:
Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.
Update the project's Startup.ConfigureServices method to include a call to AddRazorRuntimeCompilation:
services
.AddControllersWithViews()
.AddRazorRuntimeCompilation();

I've marked Kirk's answer as accepted, but maybe this experience could be useful also.
My goal was a "quick edit (cshtml/css/js/ts) then see" iteration.
No need to add and mod anything... I discovered that .NET Core (3) and VS 2019 is so much faster, so in case if we do not want to debug in VS (which is the scenario in most cases when we are changing cshtml/css/js/ts) there is really great iteration:
Press ctrl+f5 to launch your web app (no debug) in browser
See, test (debug js/ts in Chrome)
Edit your cshtml/css/js/ts
Press ctrl+shift+b to build (fast!)
Switch to your browser and press ctrl+f5 to refresh your page (fast!)
Goto 2

Related

Razor Runtime Compilation breaks Hot Reload and therefore debugging in ASP.NET

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?
It would appear that not having Razor Runtime Compilation (Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation) installed in the affected project largely mitigates this error (though the runtime still throws the occasional NullReferenceException/ExecutionEngineException while trying to reproduce the issue do my work).
As Hot Reload will also recompile your Razor views, simply uninstall the RuntimeCompilation package and you should get fewer errors.
Edit: this is not entirely true, the error popup still gets shown, albeit less frequently.
Things to try when Hot Reload won't work:
1.) Check the 'Hot Reload' output window and Error List for clues to why hot reload failed. For instance I found an error about having a 'COR_ENABLE_PROFILING' environment variable in the error list after getting the usual dialog. This appeared in the VS2022 17.5 Preview 6.0 and I'm not sure if it was there before.
2.) Make sure COR_ENABLE_PROFILING is disabled in your environment variables.
3.) Search the entire project for RuntimeCompilation (could appear in web.config, launch properties, packages) and remove them.
4.) Disable 'Native Code' debugging in your debugging profile.
5.) Restart your PC and check again

Rider Hot Reload for .NET Core WebApi not working

So basically If I make a code change, the C# application won't restart, I had to rerun manually the build project everytime I add a new line of code. This is on JetBrains Rider IDE.
So as they say in documentation, this feature is enable by default if I'm using .NET Core 6+ (which I do), I also have all checks
Any ideas so far? Or am I missing something and I need to rerun everytime I change something on the Controller with this IDE?

Hot Reload not working in Visual Studio 2022 .Net 6 Razor projects

We just upgraded all but one of our web app projects from .NET Core 3.1 projects to .NET 6 in our solution. These were ASP.NET Core 3.1 projects using Razor. Here are the results we're seeing with respect to Hot Reload:
The .NET 6 projects hot reload doesn't seem to work. Hot Reload is enabled, but our Front End is never updated. Refreshing the page doesn't seem to show the updates either.
The ASP.NET Core 3.1 project hot reload is working as expected.
When we run these projects in VS 2019, we can refresh the pages in any of our projects and we will see the updates. Are there some settings that we're missing here?
Big Thank you to Guru Stron! His comment in my question directed me to where I should've looked. We had to:
Update our Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation Nuget package
Add this to our launchsettings.json: ASPNETCORE_HOSTINGSTARTUPASSEMBLIES to "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation"
This answer solved our issue - .NET Core MVC Page Not Refreshing After Changes
First, Make sure all options are selected
In Hot reload, You can select Hot Reload On File Save(Not selected by default), Then VS will hot reload after you ctrl+s;
Demo
I had the same issue and after trying everything including rolling back the version and adding .AddRazorRuntimeCompilation() to Program.cs still didn't work. What I did was literally re-check the "Hot reload on file save" option when you click on the down arrow to bring up the menu on the hot reload button from the menu bar. That did the trick for me.
Hopefully this works for you.

.NET Core MVC Page Not Refreshing After Changes

I'm building a .NET Core MVC on the latest version 2.2. I have a problem when I make changes to the CSHTML file and refresh the page, my changes are not reflected in the browser. I have to restart the project in order to see my changes. This has been happening for a while now so I'm not exactly sure what change caused this issue.
I've tried using the chrome's "Empty Cache and Hard Reload" as well as other browsers to no avail. This happens on Windows and Mac using both Visual Studio for Mac and VS Code
In a default .Net Core project it works fine so it must be something in my project that changed along the way. I'm wondering where I need to start in order to debug this issue? I've tried commenting out almost everything in my Startup.csand Program.cs with no resolution.
In ASP.NET Core 3.0 and higher, RazorViewEngineOptions.AllowRecompilingViewsOnFileChange is not available.
Surprised that refreshing a view while the app is running did not work, I discovered the following solution:
Add Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package to the
project
Add the following in Startup.cs:
services.AddControllersWithViews().AddRazorRuntimeCompilation();
Here's the full explanation for the curious.
There was a change made in ASP.NET Core 2.2 it seems (and I can't find any announcements about this change). If you are not explicitly running in the 'Development' environment then the Razor Views are compiled and you will not see any changes made to the .cshtml
You can however turn off this using some config in your Startup class as follows.
services.AddMvc().AddRazorOptions(options => options.AllowRecompilingViewsOnFileChange = true);
For ASP.NET Core 3.0 and higher, see Alexander Christov's answer.
I've just created a new project using the latest ASP.NET MVC Core 3.1 template and I altered the following to get runtime recompilation enabled for Debug:
Reference NuGet package - Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.
Startup.cs - ConfigureServices(IServiceCollection services) WAS:
// stuff...
services.AddControllersWithViews();
// more stuff...
NOW:
// stuff...
var mvcBuilder = services.AddControllersWithViews();
#if DEBUG
mvcBuilder.AddRazorRuntimeCompilation();
#endif
// more stuff...
In addition to Alexander Christov's answer, since ASP.NET Core 3.1 you can enable the view compilation for development environment without changes to the Startup file:
Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.
Set next environment variables (for example via environmentVariables section in launchSettings.json):
ASPNETCORE_ENVIRONMENT to "Development".
ASPNETCORE_HOSTINGSTARTUPASSEMBLIES to "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation".
You should just add this:
services.AddControllersWithViews();
to the ConfigureService method.
Be aware below code is not available in ASP.NET Core 3.1:
services.AddControllersWithViews().AddRazorRuntimeCompilation();
For those using Net core 3.0 or greater
Go to Tools → Nuget package manager → Manage nuget pakages for solution
move to browse tab to browse from internet
search for RuntimeCompilation
Click on Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
install it on your intended projects the current stable version
open Startup.cs file
go to void method ConfigureServices
add line: services.AddControllersWithViews().AddRazorRuntimeCompilation();
you are DONE
Rerun and see. Now you can refresh your views or pages.
first of all install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation using nuget manager
after that add below code into your startup.cs
services.AddRazorPages().AddRazorRuntimeCompilation();
net6.0 also this works.
builder.Services.AddRazorPages().AddRazorRuntimeCompilation();
Using .net core 2.2 running app with command dotnet watch run the project is restarted after every change
Below helped me when views were in separate project.
if(HostingEnvironment.IsDevelopment()){ // only in development (optional)
services.AddMvc().AddRazorOptions(o => {
o.FileProviders.Add(new PhysicalFileProvider(PATH_TO_PROJECT));
});
}
I had the same issue while working on a .NET 6 MVC Web App.
I installed Microsoft.AspNetCore.Mvc.Razor.Runtime.Compilation from NuGet Package Manger then added .AddRazorRuntimeCompilation(); after
builder.services.AddControllersWithViews();
so that it looks like this
builder.services.AddControllersWithViews().AddRazorRuntimeCompilation();
and it worked!
Hope this helped.
I was able to solve this problem in Rider by adding the ASPNETCORE_ENVIRONMENT=Development environment variable.
There are two ways to resolve this issue:
1. Check the permissions of folder in which your .sln file present.There may be a problem with file access permissions as Visual studio may not be to access files when IIS express server is running, so to reflect new .cshtml changes each time you need to restart the server,so I suggest edit the folder access permissions by:
Right click on folder->properties->security->click on edit button -> check all options->save.
Restart Visual studio to see changes.
If this does not work then use 2 option.
2.In your project in startup.cs file add this below line ConfigureServices() in method :
services.AddMvc().AddRazorOptions(options => options.AllowRecompilingViewsOnFileChange = true);
Are you absolutely sure you are using 2.2? Check your csproj because it might be this bug https://github.com/aspnet/Razor/issues/2466
You could try turning off RazorCompileOnBuild more info https://learn.microsoft.com/en-us/aspnet/core/razor-pages/sdk?view=aspnetcore-2.1#properties
I had a similar problem upgrading from .net Core 3 to .net 5.0
Problem was due to old dependency in Telerik controls that we could not change.
Fixed by changing references in the .csproj file
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="3.8.0" />
to
<PackageReference Include="Microsoft.CodeAnalysis" Version="3.8.0" />
(your version may be different)
In Visual Studio 2022 Preview, it seems there is an option called Hot Reload for this purpose.
It seems to be available in Visual Studio 2019 too.
With Hot Reload you can now modify your apps managed source code while
the application is running, without the need to manually pause or hit
a breakpoint. Simply make a supported change while your app is running
and in our new Visual Studio experience use the “apply code changes”
button to apply your edits.
https://devblogs.microsoft.com/dotnet/introducing-net-hot-reload/

Debug setup for an ASP.NET Core app

Edit: After downgrading to .NET SDK 1.0.4, I can debug my app inside Rider and experience is pretty good.
What is the best way to set up a clean debug configuration for my ASP.NET Core app on Ubuntu in Rider 2017.1?
I want to just click on Debug button and have the tool automatically build the app, host it on some port, and open the url in browser.
Should I just try to use launchSettings.json(as VS automatically creates) or Rider offers something else?
I have .NET Command Line Tools 2.0.0-preview2-006497 installed.
You can't.
Until a new version of Rider with .Net Core support is released, debugging doesn't work.
In fact, you'll see the event log full of messages like this if you try:
12:01 PM .NET Core version problem: .NET Core 2.x is not fully supported. Some features will not work as expected.
(You can still just open a project and hit the play button and it'll run your project; but hitting the debug button doesn't actually work at the moment)
As of the time of writing, testing, nuget restore, project references (ie. between projects in the same solution) and running in debug don't work.
For now it's just a waiting game until the next version of rider comes out with these features in Fall, 2017:
We want to roll out at least two more releases this year: an inevitable bugfix release in a few weeks, and another major release (2017.2) in the Fall. Things that we expect to be addressing include support for MSTest and .NET Core 2.0, as well as releasing an SDK. We’ll certainly be keeping a close eye on your feedback (submitted via the support form, issue tracker or elsewhere) to see what other major issues need to be addressed.