I have a YARP gateway that serves static SPA files.
//...
app.MapReverseProxy();
app.MapFallbackToFile("index.html");
//...
Now I need to serve another bundle of static SPA files for a specific subdomain.
So if hostname starts with for example admin.
(never mind the domain) I need to serve the index.html
inside wwwroot/admin
, otherwise I need to serve the index.html
inside wwwroot
(which I can move to another folder as well).
How can I achieve that?
This is what worked for me, it's based on the MapFallbackToFile()
source code.
app.MapFallback(CreateRequestDelegate(app, "index.html"))
.WithMetadata(new HttpMethodMetadata(new[] { HttpMethods.Get, HttpMethods.Head }));
static RequestDelegate CreateRequestDelegate(
IEndpointRouteBuilder endpoints,
string filePath,
StaticFileOptions? options = null)
{
var app = endpoints.CreateApplicationBuilder();
app.Use(next => context =>
{
if (context.Request.Host.Host.StartsWith("admin", StringComparison.InvariantCultureIgnoreCase))
{
filePath = "admin/" + filePath;
}
context.Request.Path = "/" + filePath;
// Set endpoint to null so the static files middleware will handle the request.
context.SetEndpoint(null);
return next(context);
});
if (options == null)
{
app.UseStaticFiles();
}
else
{
app.UseStaticFiles(options);
}
return app.Build();
}
The problem with @Guru's answer was that it made the browser to download the HTML file instead of rendering it.