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?
Static files are stored within the project's web root directory. The default directory is {content root}/wwwroot , but it can be changed with the UseWebRoot method. For more information, see Content root and Web root.
Static files like JavaScript files, images, CSS files that we have on the file system are the assets that ASP.NET Core application can serve directly to clients. Static files are typically located in the web root (wwwroot) folder.
Endpoint routing configuration. The middleware pipeline endpoint route resolver middleware, endpoint dispatcher middleware and endpoint route mapping lambda is setup in the Startup. Configure method of the Startup. cs file of ASP.NET Core project.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With