net core mvc的Razor视图资源默认被预编译到了dll中,用于提高读取效率。在生产环境中正常运行这当然没有什么问题,但是当我们开发程序时可能会感觉到十分的不方便,不仅需要重新编译,而且还得必须重启web站点才能生效,试想如果我们仅仅调试页面的样式或者布局,这个简单就是一个灾难性的改动。

有没有办法设定net core mvc还是像以前那样加载cshtml文件呢?答案是有的,这个问题早已经被考虑到了。下面介绍一下如何实现,修改Razor视图后刷新页面就可以立即看到效果。

首先我们添加一个NuGet包:Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation,它是专门来解决这个问题的中间件。如下图:

nuget

再次编译我们的Startup.cs文件,告诉程序我们需要动态加载视图文件,关键代码如下:

 public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration = configuration;
            Env = env;
        }

        public IConfiguration Configuration { get; }

        public IWebHostEnvironment Env { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var builder = services.AddControllersWithViews();
            
#if DEBUG
            if (Env.IsDevelopment())
            {
                builder.AddRazorRuntimeCompilation();
            }
#endif
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

在这里我们特地指定了只有在开发环境中才启用此项,在生产环境还是从Views.dll中加载视图。

lebang2020.cn出品。