【问题标题】:Setting index.html as default page in asp.net core在 asp.net core 中将 index.html 设置为默认页面
【发布时间】:2017-03-29 10:18:01
【问题描述】:

如何让 asp.net 核心从我的 wwwroot 中提供 index.html 文件?

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

起初我尝试通过控制器返回 html 文件。我试过这条路线:

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

然后在控制器中我像这样返回 html 文件:

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

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

这不起作用。它返回了 404 not found 异常并给出了路径,但它给出的路径是 index.html 文件的正确路径(我将其剪切并粘贴到资源管理器中并打开了文件)。

我也在启动时声明这些:

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

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

本地主机:58420/index.html

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

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

【问题讨论】:

  • 是您的控制器名称HomeController
  • 是的,我在上面粘贴的操作正在触发并且具有正确的文件路径,但它给出了 404 文件未找到异常并在异常中指定了正确的路径。可能是 wwwroot 文件夹内部存在一些安全问题?
  • (I cut and pasted it into explorer and the file opened). 是的,路径绝对正确

标签: c# asp.net-core kestrel-http-server


【解决方案1】:

只需在startup.cs 中使用它:

app.UseFileServer();

它是以下的简写:

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

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

【讨论】:

  • 将此标记为答案,因为更好的解决方案
  • 如果您在新项目中无法使用它,请确保您没有在 Configure 方法的末尾保留默认的 app.Run(async (context) => await context.Response.WriteAsync("Hello World!"));。这将在您浏览到站点根目录时拦截请求,从而阻止您转到默认页面。
  • 应该突出显示 order 这个词...它至少杀死了我 30 分钟 :(
【解决方案2】:

我需要在 UseStaticFiles() 之前声明 UseDefaultFiles()。

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

【讨论】:

  • 谁因为这样的顺序而设计了行为不端的垃圾,都应该被枪杀,挂起来,然后再枪毙。两次。花了我一个小时的战斗,因为我虽然错过了一般设置或访问权限中的某些内容......为什么它们甚至会发生碰撞?!一个让我们例如JS 文件被提供,而另一个完成一个路径,例如index.html。 WTF?!
  • @KonradViltersten 这是一个管道......整个部分都按顺序进行。这样你就可以控制什么时候发生。即首先进行身份验证,然后是 MVC,等等......
【解决方案3】:

2022 年 2 月更新

要提供静态文件(例如 index.html),文件应位于项目中的文件夹 wwwroot 中。如果要将其更改为其他文件夹,请使用 UseWebRoot

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseFileServer();
}

此方法还接受 FileServerOptions 实例以进行更精细的控制,例如默认禁用的 enabling directory browsing

参考:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files

原始答案(2018 年 1 月)

安装 NuGet 包Microsoft.AspNetCore.StaticFiles

现在,在Startup.Configure 方法中,添加:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Serve the files Default.htm, default.html, Index.htm, Index.html
    // by default (in that order), i.e., without having to explicitly qualify the URL.
    // For example, if your endpoint is http://localhost:3012/ and wwwroot directory
    // has Index.html, then Index.html will be served when someone hits
    // http://localhost:3012/
    //
    // (Function 1)
    app.UseDefaultFiles();

    // Enable static files to be served. This would allow html, images, etc. in wwwroot
    // directory to be served.
    //
    // (Function 2)
    app.UseStaticFiles();
}

注意:调用这些函数的顺序很重要。在 OO 编程中,很难不依赖于排序,因为对象维护的状态在对象的生命周期内可能会发生变化。 (你猜对了,防止这种设计的一种解决方案是实现不变性。)

您现在应该从wwwroot 目录获取文件(如果您想将其更改为其他内容,请使用UseWebRoot)。

来源:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files

【讨论】:

    【解决方案4】:
    app.UseDefaultFiles(new DefaultFilesOptions {
        DefaultFileNames = new List<string> { "index.html" }
    });
    app.UseStaticFiles();
    

    这是最佳选择,因为UseDefaultFiles URL 重写器将仅搜索 index.html,而不搜索旧文件:default.htmdefault.htmlindex.htm

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.2#serve-a-default-document

    【讨论】:

      【解决方案5】:

      在 startup.cs 里面的 configureservices 方法中应用这个。这里我们创建一个 DefaultFilesOption 对象,然后清除路径中设置的所有默认文件。接下来,我们添加要设置为默认文件的路径。然后我们使用' app.UseDefaultFiles(defaultfileoptions) 注入依赖项。另外,我们需要注入静态文件作为依赖。

      `

      public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
          DefaultFilesOption defaultFileOptions = new DefaultFilesOption();
          defaultFileOptions.DefaultFileNames.Clear();
          defaultFilesOptions.DefaultFileNames.Add("Index.html");
          app.UseDefaultFiles(defaultFileOptions);
          app.UseStaticFiles();
      }  
      

      `

      【讨论】:

        【解决方案6】:

        // 默认情况下,ASP.net 核心不提供静态文件,如 HTML、css、图像等... 我需要在请求处理管道中配置中间件以提供静态文件。

        // This code would be written in Startup.cs class for configuring the middleware components.
        
        
        
          public void Configure(IApplicationBuilder app, IHostingEnvironment env)
                {
        
                app.UseDefaultFiles(); // This sets the default page redirection for the in-comming request
                    app.UseStaticFiles(); // This serves the static files to the client.
        
                }
        

        【讨论】:

          【解决方案7】:

          您正在混合使用 MVC 和默认文件服务 (useDefaultFiles)。 从您的代码中注释掉以下几行

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

          并且只使用app.UseDefaultFiles();。它将开始工作。

          【讨论】:

          • 当我取出 UseMvc...我的 api 代码停止工作。
          • @BrianRice 这是因为 MVC 对 Controller 类负责,我会假设你的 api 正在使用。
          【解决方案8】:
          return File(System.IO.File.OpenRead(Path.Combine(HostingEnvironment.WebRootPath + "/index.html")), "text/html");
          

          它必须帮助你

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-05-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-11-02
            • 2021-03-01
            • 2021-12-29
            相关资源
            最近更新 更多