英文:
Routing controller to static files
问题
我需要一个控制器,它将返回静态HTML、CSS、js和其他文件。我尝试弄清楚路由是如何工作的,但我失败了。
我尝试设置路由如下:
app.MapControllerRoute(name: "page", pattern: "Page/{pageName?}",
defaults: new { controller = "Page", action = "Index" });
我有一个PageController,其中有一个方法Index(string fileName)
,我希望当请求任何HTML页面、任何js、CSS和其他文件时,请求都会处理Index方法。
示例:
https://localhost:7177/ - 将返回index.html,
https://localhost:7177/indexStyles.css - 将返回indexStyles.css,
https://localhost:7177/indexScript.js - 将返回indexScript.js,
https://localhost:7177/user.html - 将返回user.html等等。
也就是说,我不想使用静态文件app.UseStaticFiles()
。
由于末尾的.html
,这些页面的请求看起来很糟糕。
英文:
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.
答案1
得分: 0
感谢 @Qing Guo。我的最终代码如下:
Program.cs
:
app.MapControllerRoute(name: "page", pattern: "{fileName?}",
defaults: new { controller = "Page", action = "Index" });
和 PageController
类:
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();
}
}
英文:
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();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论