Can Razor views be compiled?

2020-01-25 05:43发布

问题:

I was wondering if Razor views could be compiled, like WebForm based views?

Does it even make sense to compile Razor views and why would somebody want to do that?

回答1:

Yes, you can. Take a look at the following post: Compile your asp.net mvc Razor views into a seperate dll

It's a "step-by-step" guide on how to compile your razor views into a separate dll. I don't know if that's what you aim to do but it'll definitely get you in the right direction.



回答2:

Edit:

Here is a blog post on this topic as well:

How to Detect Errors of Our ASP.NET MVC Views on Compile Time

To make your views to be compiled, do the following;

  1. Unload your project by right clicking the project on the solution explorer in VS and clicking unload project
  2. right click the project which has been converted to unavailable project and click "Edit your_project_name.csproj" (that would be .vbproj if your project is VB project)
  3. see the following code;

    <!--There some lines of code here and I deleted them to get to the point quickly-->
    
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
    <MvcBuildViews>false</MvcBuildViews>
    

  4. change the MvcBuildViews tag value from false to true

  5. after that save it and reload your project.

after you build your solution to compile it, you will see that your view will be compiled too.

NOTE: to test it, break some code in one of your view on purpose and try to build. you will see that you'll get an error message.



回答3:

The MvcBuildViews check is excellent but it adds a 5-10 second penalty for building your web app if it's complex enough. It doesn't cache the compilation output so it does a full compilation of all your views every time.

I found a nice compromise by following the above advice and adding a Condition attribute:

<MvcBuildViews Condition=" '$(Configuration)' == 'Release' ">true</MvcBuildViews>

We'd expect ReSharper to flag up any errors in the views anyway and the developer can always build in the release configuration as a test - we have a "preflight" script that developers run so they can easily make sure that package targets work and so on - and if all that fails, the build server will catch it.

Perhaps this trick is obvious but I've only really started learning about msbuild properly as opposed to writing Powershell scripts for these tasks. I hope this is helpful to someone.



回答4:

Yes, it's possible. In fact, the best example I can think of would be email templating engines. If you compile and cache the template, then you can quickly rip off emails without having to go through the parsing all over again.

That's a good example of using Razor outside of MVC as well.