ASP.NET MVC - Update Pre-compiled Razor View file

2020-07-14 05:34发布

问题:

I was wondering if the following is possible :

  1. Precompile the Razor views with our MVC app by turning on the project setting in visual studio.
  2. Deploy the app to production.
  3. Then at a later stage, update the views by overwriting the existing *.cshtml files in production without recycling the app pool or re-compiling the project and re-deploying the build.?

回答1:

Yes you can do this. The view engine will recompile all the files in each directory into a separate DLL into a file like this

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\micropedi_mvc\d3b5b4cd\eb219373\App_global.asax.ihdiifed.DLL

You can use ILSpy or Reflector to open up this file and see exactly which files were compiled to it. if you have many directories you'll see several DLLs generated.

Note that all thatMvcBuildViews` does is run this post build event which just does the same as if you were to hit each file needed for your application.

<Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
   <AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" />
</Target>

For maximum performance I'd recommend the RazorGenerator precompiler. This actually embeds the cshtml files into your main DLL which isn't what MvcBuildViews does at all. Plus its much faster.

If you wanted to use this in production you'd need to change UsePhysicalViewsIfNewer in RazorGeneratorMvcStart.cs to true so that it would recompile if you updated the view.


Tip: If you ever want to find exactly which DLL the cshtml file is compiled to just add this to your page

 <div>This file is compiled to  @this.GetType().Assembly.CodeBase</div> 

Then you'll get the full path without looking for it.



回答2:

Yes, you can.

cshtml files don't get compiled like the rest of your project. So you can change them outside of your project.