有时为了方便调试,当修改cshtml文件时,不需要重新编译,操作方法如下
- 如果是新项目,在创建项目时“启用Razor运行时编译”打勾即可
- 如果是现有项目
方法1(原理同上):
1.项目右键->编辑项目文件:
1 <Project Sdk="Microsoft.NET.Sdk.Web"> 2 <PropertyGroup> 3 <TargetFramework>netcoreapp3.1</TargetFramework> 4 <CopyRefAssembliesToPublishDirectory>false</CopyRefAssembliesToPublishDirectory> 5 </PropertyGroup> 6 <ItemGroup> 7 <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.3" /> 8 </ItemGroup> 9 </Project>
2.launchSettings.json
"profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" } }, "WebApplication4": { "commandName": "Project", "launchBrowser": true, "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" } } }
方法2:
1.编辑项目文件如下
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.3" Condition="'$(Configuration)' == 'Debug'" />
</ItemGroup>
</Project>
2.修改startp.cs文件
public class Startup { public Startup(IConfiguration configuration, IWebHostEnvironment env) { Configuration = configuration; Env = env; } public IWebHostEnvironment Env { get; set; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { IMvcBuilder mvcBuilder = services.AddControllersWithViews(); #if DEBUG if (Env.IsDevelopment()) mvcBuilder.AddRazorRuntimeCompilation(); #endif }
最后:以上无论哪种方法都加上这个条件后,会使用发布后的文件夹比较干净
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.3" Condition="'$(Configuration)' == 'Debug'" />
未添加 Condition="'$(Configuration)' == 'Debug'"
添加 Condition="'$(Configuration)' == 'Debug'"后: