开发mvc过程中razor页面需要重启才能编译,非常麻烦,能否实现动态编译,微软官方提供了一个包能实现
新建.net 6 mvc项目
安装Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
修改csproj
<Project Sdk="Microsoft.NET.Sdk.Web"><PropertyGroup><!--下面两行代码是生产环境使用需要添加,测试环境无需处理csproj--><MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish><RazorCompileOnBuild>false</RazorCompileOnBuild></PropertyGroup>
</Project>
修改program.cs
namespace WebApplication2;public class Program
{public static void Main(string[] args){var builder = WebApplication.CreateBuilder(args);var mvcBuilder = builder.Services.AddControllersWithViews();//核心代码在这if (builder.Environment.IsDevelopment()){//添加razor页面动态编译mvcBuilder.AddRazorRuntimeCompilation();}var app = builder.Build();app.UseRouting();app.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");app.Run();}
}
目前测试.net8不行
参考
https://github.com/dotnet/aspnetcore/issues/52248
https://techcommunity.microsoft.com/t5/net-runtime/net-8-0-2-update-causes-asp-net-core-mvc-index-view-not-found/m-p/4058976
https://cloud.tencent.com/developer/article/1020241
https://learn.microsoft.com/zh-cn/aspnet/core/mvc/views/view-compilation?view=aspnetcore-8.0&tabs=visual-studio
https://www.cnblogs.com/rupeng/p/15872803.html