Reputation: 47
I’m working on an ASP.NET Core application and need to configure it to serve static files from multiple directories. I’m encountering unexpected behavior where files placed in the original wwwroot folder are still being served even though I’ve renamed wwwroot and configured new directories.
Here’s what I’ve done:
I created a folder named myRoot and set it as the WebRootPath in the application configuration.
var builder = WebApplication.CreateBuilder(new WebApplicationOptions()
{
WebRootPath = "myRoot"
});
var app = builder.Build();
// Enable serving static files from myRoot
app.UseStaticFiles();
I added another folder called myWebRoot to serve static files from.
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "myWebRoot")),
RequestPath = "/myWebRoot"
});
Expected Behavior:
Actual Behavior:
Questions:
Additional Information:
Code and Screenshots:
Here’s a screenshot showing the folder structure and configuration
Full Code:
using Microsoft.Extensions.FileProviders;
var builder = WebApplication.CreateBuilder(new WebApplicationOptions()
{
WebRootPath = "myRoot"
});
var app = builder.Build();
// Enable serving static files
app.UseStaticFiles(); // works with the web root path
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath , "myWebRoot"))
}); // works with myWebRoot
app.MapGet("/", async (context) =>
{
await context.Response.WriteAsync("Hello");
});
app.Run();
Thank you for any help or insights!
Upvotes: 0
Views: 137
Reputation: 22029
I am using below code, it works for me.
Program.cs
using Microsoft.Extensions.FileProviders;
// change the root path like below
string basedir = AppDomain.CurrentDomain.BaseDirectory;
WebApplicationOptions options = new()
{
ContentRootPath = basedir,
Args = args,
WebRootPath = Path.Combine(basedir, "myRoot")
};
var builder = WebApplication.CreateBuilder(options);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "myWebRoot")),
RequestPath = "/myWebRoot"
});
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Upvotes: 0