I need a controller that will return static HTML, CSS, js, and other files. I tried to figure out how routing works, but I failed.
I've tried setting up routing like this:
app.MapControllerRoute(name: "page", pattern: "Page/{pageName?}",
defaults: new { controller = "Page", action = "Index" });
I have a PageController with a single method Index(string fileName)
and I want that when requesting any HTML page, any js, CSS, and other files, the request would process the Index method.
Example:
https://localhost:7177/ - will return index.html,
https://localhost:7177/indexStyles.css - will return indexStyles.css,
https://localhost:7177/indexScript.js - will return indexScript.js,
https://localhost:7177/user.html - will return user.html and so on.
That said, I don't want to use static files app.UseStaticFiles()
.
The request to such pages looks terrible because of the .html on the end.
thanks to @Qing Guo. My final code looks like this:
Program.cs
:
app.MapControllerRoute(name: "page", pattern: "{fileName?}",
defaults: new { controller = "Page", action = "Index" });
and PageController
class:
public IActionResult Index(string fileName)
{
if (fileName == null)
{
return File("index.html", "text/html");
}
string fileFormat = Path.GetExtension(fileName);
if (fileFormat == "")
fileName += ".html";
fileFormat = Path.GetExtension(fileName);
if (System.IO.File.Exists($"wwwroot/{fileName}"))
{
string contentType = $"text/{fileFormat[1..]}";
if (fileFormat == ".jpg")
contentType = "image/jpg";
return File($"{fileName}", contentType);
}
else
{
return NotFound();
}
}