razor views 默认是在运行时才编译的。为了更好的性能,预编译 razor views 是一个理想的方案。
用 Nuget 安装RazorGenerator.Mvc
和RazorGenerator.MsBuild
两个包到项目里
RazorGenerator.Mvc 包会在你的 App_Start 下创建一个 RazorGeneratorMvcStart.cs 文件。
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
using RazorGenerator.Mvc;
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(MvcAppTest.RazorGeneratorMvcStart), "Start")]
namespace MvcAppTest {
public static class RazorGeneratorMvcStart {
public static void Start() {
var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly) {
UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
};
ViewEngines.Engines.Insert(0, engine);
// StartPage lookups are done by WebPages.
VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
}
}
}
csproj文件中会增加一下配置
<Import Project="..\packages\RazorGenerator.MsBuild.2.5.0\build\RazorGenerator.MsBuild.targets" Condition="Exists('..\packages\RazorGenerator.MsBuild.2.5.0\build\RazorGenerator.MsBuild.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\RazorGenerator.MsBuild.2.5.0\build\RazorGenerator.MsBuild.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\RazorGenerator.MsBuild.2.5.0\build\RazorGenerator.MsBuild.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target> -->
在你项目的csproj文件中添加一下数据
<Target Name="BeforeBuild">
<ItemGroup>
<Content Remove="Views\**\*.cshtml" />
<None Include="Views\**\*.cshtml" />
</ItemGroup>
</Target>
我添加了BeforeBuild Target 在the RazorGenerator.targets的后面。BeforeBuild
target提供了在pre-build事件之前要做的事情。现在我们把移除所有的.cshtml
从内容类型中移除,并设置为不引入。现在,当应用程序构建时,页面就再也不会以内容类型拷贝到发布目录里了。
如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。
本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。