這是從 ASP.NET Core 1.1 官方發布博文中學到的一招,可以在 dontet publish 時將 Razor 視圖編譯為 .dll 文件。
需要在 project.json 中添加如下配置:
1)在 "dependencies" 中添加:
"Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.Design": "1.1.0-preview4-final"
2)在"tools"中添加:
"tools": { "Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.Tools": "1.1.0-preview4-final" }
3)在"scripts"中添加:
"scripts": { "postpublish": "dotnet razor-precompile --configuration %publish:Configuration% --framework %publish:TargetFramework% --output-path %publish:OutputPath% %publish:ProjectPath%" }
然后在運行 dotnet publish 命令時就會編譯 ASP.NET Core 項目中的 Razor 視圖:
Running Razor view precompilation. Precompiled views emitted to /data/AboutUs/bin/release/netcoreapp1.1/ubuntu.14.04-x64/publish/AboutUs.PrecompiledViews.dll. Successfully compiled 18 Razor views in 12734ms.
MVC Razor 視圖被編譯成了一個 AboutUs.PrecompiledViews.dll 文件,運行站點時只需要這個 dll 文件,不需要 .cshtml 視圖文件了。
- 2017年4月21日更新
ASP.NET Core 之后更新了預編譯視圖的使用方法,現在只需安裝 NuGet 包 Microsoft.AspNetCore.Mvc.Razor.ViewCompilation,然后在 .csproj 中添加如下的配置:
<MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>