静态文件服务
静态文件能够被保存在网站根目录下的任意文件夹内,并通过相对根的路径来访问。比方说,当你通过 Visual Studio 创建一个默认的 Web 应用程序项目,在 wwwroot 目录下会多出几个文件夹:css、images 以及 js 文件夹。为了能够启用静态文件服务,你必须配置中间件(middleware),把静态文件中间件加入到管道内。
默认文档服务
设置默认首页能给你的站点的每个访问者提供一个起始页。为使站点能提供默认页,避免用户输入完整 URI,须在 Startup.Configure 中调用 UseDefaultFiles 扩展方法。
UseDefaultFiles 必须在 UseStaticFiles 之前调用。UseDefaultFiles 只是重写了 URL,而不是真的提供了这样一个文件。你必须开启静态文件中间件(UseStaticFiles)来提供这个文件。
通过 UseDefaultFiles,请求文件夹的时候将检索以下文件:
- default.htm
- default.html
- index.htm
- index.html
//设置启动默认页
DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
defaultFilesOptions.DefaultFileNames.Clear();
defaultFilesOptions.DefaultFileNames.Add(“1.html”);
app.UseDefaultFiles(defaultFilesOptions);//设置启动默认页
访问指定非wwwroot文件下静态文件
UseFileServer
UseFileServer 包含了 UseStaticFiles 、UseDefaultFiles 和 UseDirectoryBrowser 的功能。
app.UseFileServer();//启用了静态文件和默认文件,但不允许直接访问目录。
app.UseFileServer(enableDirectoryBrowsing: true);//启用了静态文件、默认文件和目录浏览功能。
查看直接提供目录访问时的安全风险注意事项。作为一个集合了 UseStaticFiles、UseDefaultFiles 和 UseDirectoryBrowser 方法于一体的方法,如果你希望提供 web root 之外存在的文件,你要实例化并配置一个 FileServerOptions 对象传递给 UseFileServer 的参数
总结:
- ASP.Net Core默认不支持静态文件的服务
- 默认的静态服务文件夹为wwwroot
- 要使用静态文件,必须使用UseStaticFiles()中间件
- 要定义默认文件,必须使用UseDefaultFiles ()中间件
- 默认支持的文件列表:Index.htm Index.html Default.htm Default.html
- UseDefaultFiles()必须注册在UseStaticFiles()前面UseFileServer结合了UseStaticFiles
- UseFileServer结合了UseStaticFiles, UseDefaultFiles和UseDirectoryBrowser中间件的功能。
参考:
https://www.w3cschool.cn/netcore/netcore-jhay31l1.html
https://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-3_3-static-files.html