Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core MVC Page Not Refreshing After Changes

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:

  1. Add Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package to the project

  2. 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:

  1. Install the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package.
  2. 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

  1. Go to Tools → Nuget package manager → Manage nuget pakages for solution

  2. move to browse tab to browse from internet

  3. search for RuntimeCompilation Click on Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation

  4. install it on your intended projects the current stable version

  5. open Startup.cs file

  6. go to void method ConfigureServices

  7. add line: services.AddControllersWithViews().AddRazorRuntimeCompilation();

  8. you are DONE

Rerun and see. Now you can refresh your views or pages.