I am building a single page web application in ASP .NET Core which requires me to map some URLs to an endpoint which serves a specific static file called "index.html".
Currently, I used a hack solution which maps all URLs to the endpoint.
_ = app.UseEndpoints(endpoints => {
_ = endpoints.MapControllers();
_ = endpoints.MapGet("/test", async context => {
// I need some way to serve the static file in the response
await context.Response.WriteAsync("Hello world");
});
// TODO replace with actual endpoint mapping
//_ = endpoints.MapFallbackToFile("index.html");
});
Instead, I would like to map only a specific set of URLs to the endpoint. How do I accomplish this?
The solution was to implement URL rewriting to rewrite URLs to index.html as well as add use default files for the "/" root URL.
RewriteOptions rewriteOptions = new RewriteOptions()
.AddRewrite("test", "index.html", true);
_ = app.UseRewriter(rewriteOptions);
_ = app.UseDefaultFiles();
This section of code comes before the UseRouting middleware call.