在ASP.NET Core中将index.html设置为默认页面 [英] Setting index.html as default page in asp.net core

查看:678
本文介绍了在ASP.NET Core中将index.html设置为默认页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取asp.net核心以从wwwroot内提供index.html文件?

How can I get asp.net core to serve an index.html file from inside my wwwroot?

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

The reason I want to do this is because I an developing an angular 4 app using the angular CLI and it takes care of the entire build process. I have set it up to build into the wwwroot directory of my asp.net core project but asp.net core doesn't want to serve it.

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

At first I tried to return the html file through a controller. I tried this route:

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

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

And then in the controller I return the html file like this:

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文件的正确路径(我将其剪切并粘贴到资源管理器中并打开了文件).

This didn't work. It returned a 404 not found exception and gave the path but the path it gave was the correct path to the index.html file (I cut and pasted it into explorer and the file opened).

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

I am also declaring these in startup:

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

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

I then tried removing the default route. Now I am able to get to the index.html file but only if I type the filename in, i.e.:

localhost:58420/index.html

localhost:58420/index.html

如果我尝试访问未指定"index.html"的域的根目录,则会收到404错误.

If I try to access the root of the domain without the "index.html" specified I get a 404 error.

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

What is the proper way to reference the index.html as the default page? I am guessing doing it from a controller is probably better because then it will be compatible with angular routing without rewrites.

推荐答案

只需在startup.cs中使用它:

app.UseFileServer();

它的简写:

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

避免了必须按正确顺序 进行操作的问题(如上所示)

it avoids issues with having to have those in the correct order (as shown above)

这篇关于在ASP.NET Core中将index.html设置为默认页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆