gpt4 book ai didi

c# - 在 asp.net core 中将 index.html 设置为默认页面

转载 作者:IT王子 更新时间:2023-10-29 04:18:06 26 4
gpt4 key购买 nike

如何让 asp.net core 为我的 wwwroot 中的 index.html 文件提供服务?

我想这样做的原因是因为我正在使用 Angular CLI 开发一个 Angular 4 应用程序,它负责整个构建过程。我已将其设置为构建到我的 asp.net 核心项目的 wwwroot 目录中,但 asp.net 核心不想为其提供服务。

起初我试图通过 Controller 返回 html 文件。我试过这条路线:

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});

然后在 Controller 中我返回这样的 html 文件:

public IActionResult Index()
{
var webRoot = _env.WebRootPath;
var path = System.IO.Path.Combine(webRoot, "index.html");

return File(path, "text/html");
}

这没有用。它返回 404 未找到异常并提供路径,但它提供的路径是 index.html 文件的正确路径(我将其剪切并粘贴到资源管理器中并打开了文件)。

我也在启动时声明了这些:

app.UseStaticFiles();
app.UseDefaultFiles();

然后我尝试删除默认路由。现在我可以访问 index.html 文件,但前提是我输入文件名,即:

localhost:58420/index.html

如果我尝试在没有指定“index.html”的情况下访问域的根目录,我会收到 404 错误。

将 index.html 引用为默认页面的正确方法是什么?我猜想从 Controller 做这件事可能会更好,因为这样它就可以与角度路由兼容而无需重写。

最佳答案

只需在 startup.cs 中使用它:

app.UseFileServer();

它是以下内容的简写:

app.UseDefaultFiles();
app.UseStaticFiles();

避免了必须以正确的顺序(如上所示)的问题

关于c# - 在 asp.net core 中将 index.html 设置为默认页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com