a-lion
a-lion

Reputation: 11

ASP.NET is there a way to map a specific endpoint to a static html file?

i would like to map a custom endpoint to an html file like localhost:3000/page taking you to somePage.html. I tried using app.UseFileServer as described in the asp.net docs for static files like this

app.UseFileServer(new FileServerOptions
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\somePage.html")),
    RequestPath = "/page",
});

but i realized it is meant for mapping a directory not individual files and nothing else on that page seemed to do what i want, unless i missed it.

i also thought about using a redirect like this

app.MapGet("/page", () => Results.Redirect("/somePage.html"));

but i don't want the url to be localhost:3000/somePage.html, i want it to be localhost:3000/page. so i can't use that.

i figured i could just read the file to a variable and return it like this

string currDir = Directory.GetCurrentDirectory();
byte[] somePageHtml = File.ReadAllBytes(Path.Combine(currDir, @"wwwroot\somePage.html"));

app.MapGet("/page", () =>
{
    return Results.File(somePageHtml, "text/html");
});

which works, but i was wondering is there is a way i am supposed to do this in asp.net? also could my method cause problems in the future? i don't know how many or how big my html files will be, is it a bad idea to keep them in memory like this?

Upvotes: 0

Views: 72

Answers (1)

Niall O'Dwyer
Niall O'Dwyer

Reputation: 103

Create a View and Controller for "SomePage" Inject the Raw HTML into the view @Html.Raw(System.IO.File.ReadAllText("/Somelocation/SomePage.html"));

Upvotes: 0

Related Questions