Gue*_*lla 28 c# kestrel-http-server asp.net-core
如何从我的wwwroot中获取asp.net核心来提供index.html文件?
我想这样做的原因是因为我使用角度CLI开发了一个角度4应用程序,它负责整个构建过程.我已将其设置为我的asp.net核心项目的wwwroot目录,但asp.net核心不想提供它.
起初我试图通过控制器返回html文件.我尝试过这条路线:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
});
Run Code Online (Sandbox Code Playgroud)
然后在控制器中我返回如下的html文件:
public IActionResult Index()
{
var webRoot = _env.WebRootPath;
var path = System.IO.Path.Combine(webRoot, "index.html");
return File(path, "text/html");
}
Run Code Online (Sandbox Code Playgroud)
这没用.它返回了404未找到的异常并给出了路径,但它给出的路径是index.html文件的正确路径(我将其剪切并粘贴到资源管理器中并打开文件).
我也在启动时声明这些:
app.UseStaticFiles();
app.UseDefaultFiles();
Run Code Online (Sandbox Code Playgroud)
然后我尝试删除默认路由.现在我能够访问index.html文件,但仅当我输入文件名时,即:
本地主机:58420/index.html的
如果我尝试在没有指定"index.html"的情况下访问域的根目录,则会收到404错误.
将index.html作为默认页面引用的正确方法是什么?我猜测从控制器做它可能更好,因为它将与角度路由兼容而无需重写.
Chr*_*row 37
只需使用此startup.cs:
app.UseFileServer();
Run Code Online (Sandbox Code Playgroud)
它是以下的简写:
app.UseDefaultFiles();
app.UseStaticFiles();
Run Code Online (Sandbox Code Playgroud)
......它避免了必须按正确顺序排列的问题
Gue*_*lla 32
我需要在UseStaticFiles()之前声明UseDefaultFiles().
app.UseDefaultFiles();
app.UseStaticFiles();
Run Code Online (Sandbox Code Playgroud)
app.UseDefaultFiles(new DefaultFilesOptions {
DefaultFileNames = new List<string> { "index.html" }
});
app.UseStaticFiles();
Run Code Online (Sandbox Code Playgroud)
这是最佳选择,因为UseDefaultFilesURL 重写器将仅搜索index.html,而不搜索旧文件:default.htm、default.html和index.htm。
安装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/
app.UseDefaultFiles();
// Enable static files to be served. This would allow html, images, etc. in wwwroot
// directory to be served.
app.UseStaticFiles();
}
Run Code Online (Sandbox Code Playgroud)
现在,您应该从wwwroot目录中获取文件(UseWebRoot如果您想将其更改为其他文件,则可以使用)。
来源:https : //docs.microsoft.com/zh-cn/aspnet/core/fundamentals/static-files
| 归档时间: |
|
| 查看次数: |
22848 次 |
| 最近记录: |