'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?



Solution 1:[1]

You can use the Microsoft.AspNetCore.SpaServices.Extensions

public void ConfigureServices(IServiceCollection services)
{
  // ...

  services.AddSpaStaticFiles(configuration =>
  {
    configuration.RootPath = "static"; // Path to your index.html
  });

  // ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  // ...

  app.Map("/yourSpaRoute", spaApp=>
  {
    spaApp.UseSpa(spa =>
    {
      spa.Options.SourcePath = "/static"; // source path
    });
  });

   // ...     
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Moe Howard