我怎样才能让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");
}
这不管用。它返回了一个404not found异常,并给出了路径,但它给出的路径是index.html文件的正确路径(我将其剪切并粘贴到资源管理器中,然后文件就打开了)。
我在启动时也声明了这些:
app.UseStaticFiles();
app.UseDefaultFiles();
然后,我尝试删除默认路由。现在,我可以访问index.html文件,但前提是我必须键入文件名,即:
本地主机:58420/index.html
如果我试图在没有指定"index.html“的情况下访问域的根目录,我会得到一个404错误。
引用index.html作为默认页面的正确方式是什么?我猜在控制器上做可能会更好,因为这样它就可以在不重写的情况下与angular路由兼容。
发布于 2018-06-28 06:15:18
只需在startup.cs
中使用它
app.UseFileServer();
它是以下的简写:
app.UseDefaultFiles();
app.UseStaticFiles();
它避免了那些必须在正确的顺序中的问题(如上所示)
发布于 2017-03-29 18:58:44
我需要在UseStaticFiles()之前声明UseDefaultFiles()。
app.UseDefaultFiles();
app.UseStaticFiles();
发布于 2018-01-05 07:33:08
安装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
https://stackoverflow.com/questions/43090718
复制相似问题