Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map an endpoint to a static file in ASP. NET Core?

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?

like image 875
shertu Avatar asked Jun 14 '20 12:06

shertu


People also ask

Where do I put static files in NET Core?

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.

What are static files in ASP.NET Core?

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.

Which file contains the endpoint route configuration in ASP.NET Core?

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.


1 Answers

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.

like image 116
shertu Avatar answered Oct 25 '22 18:10

shertu