【问题标题】:Specifying default file name for asp.net core static folder为 asp.net core 静态文件夹指定默认文件名
【发布时间】:2017-02-16 16:53:53
【问题描述】:

我目前在一个文件夹中生成了 index.html、js 和其他静态文件,我将该文件夹标记为静态文件夹(通过在 Startup.cs 的 Configure 方法中添加以下内容:

   app.UseDefaultFiles();
   app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new Path.Combine(env.ContentRootPath, @"../build")),
        RequestPath = new PathString("/app/")
    });

有没有办法将 index.html 设置为此 */app 路由的默认响应?因为现在 localhost:5000/app/ 返回 404 而 localhost:5000/app/index.html 返回 index.html。

编辑:我错过了提到我确实尝试使用 app.UseDefaultFiles() 就像docs 中提到的那样,但它对我不起作用。服务器仍然返回 404

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-core


【解决方案1】:

docs 中的一位 cmets 已经澄清了这一点:

基伦_约翰斯通 2017 年 5 月 22 日精选

“提供默认文档”部分遗漏了一些重要的内容 信息。如果您将 UseStaticFiles 配置为使用 非根 RequestPath,您需要传递相同的 FileProvider 和 RequestPath 到 UseDefaultFiles 和 UseStaticFiles,似乎。 您不能总是按照章节中的说明来称呼它。

也就是说,你应该写这样的东西来让你指定的文件夹提供一个默认页面:

    app.UseDefaultFiles(new DefaultFilesOptions()
    {
        FileProvider = Path.Combine(env.ContentRootPath, @"../build")),
        RequestPath = new PathString("/app/")
    });
    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = Path.Combine(env.ContentRootPath, @"../build")),
        RequestPath = new PathString("/app/")
    });

【讨论】:

  • .NET Core 5.0 仍然是这种情况,以防有人遇到它。
【解决方案2】:

使用这个:

public void Configure(IApplicationBuilder app)
{
    // Serve my app-specific default file, if present.
    DefaultFilesOptions options = new DefaultFilesOptions();
    options.DefaultFileNames.Clear();
    options.DefaultFileNames.Add("mydefault.html");
    app.UseDefaultFiles(options);
    app.UseStaticFiles();
}

更多详情请点击此链接:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files
and go to section: "Serving a default document"

【讨论】:

  • 他有index.html,UseDefaultFiles()默认包含,不用添加mydefault.html
【解决方案3】:

来自documentation:

设置默认主页为网站访问者提供了一个起点 访问您的网站。为了让您的 Web 应用程序提供默认页面 无需用户完全限定 URI,调用 从 Startup.Configure 中的 UseDefaultFiles 扩展方法如下。

public void Configure(IApplicationBuilder app)
{
    app.UseDefaultFiles();
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), @"build")),
        RequestPath = new PathString("/app")
    });
}

必须在 UseStaticFiles 之前调用 UseDefaultFiles 才能为 默认文件。

【讨论】:

  • 感谢您回来。我试过了,但仍然返回 404。如果使用不同的静态文件夹(除了 wwwroot),这是否有效?
  • @ArvindVenkataraman,您的应用程序文件夹实际位于何处?
猜你喜欢
  • 1970-01-01
  • 2020-08-28
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 2018-12-04
  • 2018-07-19
  • 2018-02-28
相关资源
最近更新 更多