In my web application, I have a controller with a fallback-route so that every request goes to this controller, and additionally I use the PhysicalFileProvider
to serve static files from a specific directory.
My fallback controller:
[ApiController]
[AllowAnonymous]
[Route("")]
public class PageRenderingController : ControllerBase
{
[HttpGet("{*url:nonfile}")]
public async Task<ActionResult> Get([FromRoute]string? url = null)
{
// return result
}
}
My Program.cs
:
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// register services...
var app = builder.Build();
SetupFileServer(app);
app.MapControllers();
app.Run();
}
private static void SetupFileServer(WebApplication app)
{
var staticAdminFileServerOptions = new FileServerOptions
{
EnableDefaultFiles = true,
FileProvider = new PhysicalFileProvider(
Path.Combine(app.Environment.ContentRootPath, "_admin")),
RequestPath = "/admin",
EnableDirectoryBrowsing = false,
};
app.UseFileServer(staticAdminFileServerOptions);
}
So my problem now is that even I registered the FileServer
before the controllers, a request to http://host/admin/
goes to the controller instead of the FileServer
(and serving the index.html
file). Any ideas how to solve that?
I tested your code and found that the problem occurred in the call of the app.UseRouting()
; middleware. You need to configure the corresponding configuration request routing for the project. If it is not configured, it will still be captured by the controller.
When I configured the corresponding middleware and visited http://host/admin
again, I could see that the index page was fully rendered:
using Microsoft.Extensions.FileProviders;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
SetupFileServer(app);
// 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.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
static void SetupFileServer(WebApplication app)
{
var staticAdminFileServerOptions = new FileServerOptions
{
EnableDefaultFiles = true,
FileProvider = new PhysicalFileProvider(
Path.Combine(app.Environment.ContentRootPath, "admin")),
RequestPath = "/admin",
EnableDirectoryBrowsing = false,
};
app.UseFileServer(staticAdminFileServerOptions);
}