首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在asp.net核心中将index.html设置为默认页面

在asp.net核心中将index.html设置为默认页面
EN

Stack Overflow用户
提问于 2017-03-29 18:18:01
回答 8查看 41.1K关注 0票数 44

我怎样才能让asp.net核心从我的wwwroot内部提供index.html文件?

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

首先,我试图通过一个控制器返回html文件。我尝试了以下方法:

代码语言:javascript
复制
app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}");
    });

然后在控制器中返回html文件,如下所示:

代码语言:javascript
复制
public IActionResult Index()
{
    var webRoot = _env.WebRootPath;
    var path = System.IO.Path.Combine(webRoot, "index.html");

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

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

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

代码语言:javascript
复制
app.UseStaticFiles();
app.UseDefaultFiles();

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

本地主机:58420/index.html

如果我试图在没有指定"index.html“的情况下访问域的根目录,我会得到一个404错误。

引用index.html作为默认页面的正确方式是什么?我猜在控制器上做可能会更好,因为这样它就可以在不重写的情况下与angular路由兼容。

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2018-06-28 06:15:18

只需在startup.cs中使用它

代码语言:javascript
复制
app.UseFileServer();

它是以下的简写:

代码语言:javascript
复制
app.UseDefaultFiles();
app.UseStaticFiles();

它避免了那些必须在正确的顺序中的问题(如上所示)

票数 74
EN

Stack Overflow用户

发布于 2017-03-29 18:58:44

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

代码语言:javascript
复制
app.UseDefaultFiles();
app.UseStaticFiles();
票数 36
EN

Stack Overflow用户

发布于 2018-01-05 07:33:08

安装NuGet包Microsoft.AspNetCore.StaticFiles

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

代码语言:javascript
复制
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

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43090718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档