ASP.Net Core 的Web项目,对于静态资源目录的自定义场景有以下几种常见场景。
(1)更改默认 wwwroot目录
ASP.Net Core Web 静态资源默认目录为 {content root}/wwwroot,但可通过 UseWebRoot 方法更改目录。使用方法如下:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webHostBuilder =>
{
webHostBuilder.UseWebRoot(@".\myfiles\");
webHostBuilder.UseStartup<Startup>();
});
注意以上方法只是更改了wwwroot的默认目录。
(2)多个静态资源目录
此应用场景主要是除保留原来的目录外,还需要添加额外的目录。
/ 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(new StaticFileOptions
{
FileProvider = new CompositeFileProvider(env.WebRootFileProvider, new PhysicalFileProvider(Path.Combine(env.WebRootPath, "plugins")))
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}").RequireAuthorization();
});
}
可以看到我们使用了StaticFileOptions,里面默认的FileProvider 是env.WebRootFileProvider,除了它我们还可以使用CompositeFileProvider来扩展新的目录。
参考:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files?view=aspnetcore-5.0
同时文件引擎可以参考我的另一篇文章:https://www.lebang2020.cn/details/210312ejftdcyo.html