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>(); }); }