asp.core支持多个静态文件目录以及指定默认页的配置

  Asp.Core中使用静态文件目录,默认情况下直接使用app.UseStaticFiles(),会将站点下的wwwroot文件夹作为静态文件目录,如果想支持多个文件夹作为静态文件目录可以借助CompositeFileProvider类来配置

   //开启多个静态文件目录
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new CompositeFileProvider(new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, "wwwroot")),
                                                         new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, "myweb"))),
            }); 

  这样wwwroot,myweb下的静态文件就可以访问了。

  但是开启多静态目录后指定的默认页面的就不能访问了,可能是因为性能问题,core并不会遍历所有文件夹帮你找默认页面,研究了一番有两种方法来解决这个问题:

  1. 不使用app.UseDefaultFiles()来配置默认页了,通过默认路由配置跳转到/home/index 控制器中,在index方法中返回默认页面数据:

app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();  //默认控制器路由
            });


 public class HomeController : ControllerBase
    {
        public ActionResult Index()
        {
            var path = Path.Combine(AppContext.BaseDirectory, "wwwroot\index.html");
            return PhysicalFile(path, "text/html");  //直接返回index.html内容
        }
    }

  2. 继续使用app.UseDefaultFiles()来配置默认页,同时在IWebHostBuilder启动配置时调用UseWebRoot()指定WebRoot目录

   //Startup.Configure方法中的代码
   var options = new DefaultFilesOptions();
   options.DefaultFileNames.Clear();
   options.DefaultFileNames.Add("index.html"); //指定默认文件
   app.UseDefaultFiles(options);

   //开启多个静态文件目录
   app.UseStaticFiles(new StaticFileOptions
   {
            FileProvider = new CompositeFileProvider(new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, "wwwroot")),
                                                     new PhysicalFileProvider(Path.Combine(AppContext.BaseDirectory, "myweb"))),
   });

  app.UseEndpoints(endpoints =>
  {
        //endpoints.MapDefaultControllerRoute(); 
        endpoints.MapControllers();
   });


  public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder
                    .UseWebRoot(Path.Combine(AppContext.BaseDirectory, "wwwroot"))     //加上这句 默认文件配置会生效
                    .UseStartup<Startup>();
                });
    }

  

  

    

 
原文地址:https://www.cnblogs.com/zhangmingjian/p/14087745.html