静态文件中间件的能力
- 支持指定相对路径
- 支持目录浏览
- 支持设置默认文档
- 支持多目录映射
代码实现
创建项目
创建名字为StaticFilesDemo
的ASP.NET Core
项目,类型为API
创建测试用的静态文件
在根目录创建wwwroot
文件夹,参照下面结构进行对应文件创建:
1 | wwwroot |
具体代码如下:
/wwwroot/index.html
1 |
|
/wwwroot/app.js
1 | alert("这是/index.html") |
/wwwroot/a/index.html
1 |
|
/wwwroot/a/a.js
1 | alert("这是/a/index.html") |
默认静态文件中间件
在Startup.Configure
中,将以下代码添加到app.UseHttpsRedirection();
下一行
1 | app.UseStaticFiles(); |
运行项目访问https://localhost:5001/index.html
和https://localhost:5001/a/index.html
可看到静态页面信息
设置默认文件为index.html
能起到的效果如下:
https://localhost:5001
= https://localhost:5001/index.html
https://localhost:5001/a
= https://localhost:5001/a/index.html
在app.UseStaticFiles();
前面添加以下代码即可:
1 | app.UseDefaultFiles(); |
运行项目访问https://localhost:5001
和https://localhost:5001/a
可看到静态页面信息
支持目录浏览
注释掉默认文件的那个中间件,添加目录浏览的中间件,代码如下:
1 | app.UseDirectoryBrowser(); |
然后在Startup.ConfigureServices
配置目录浏览的服务,代码如下:
1 | services.AddDirectoryBrowser(); |
运行项目访问https://localhost:5001
,可以看到wwwroot
的目录结构
多目录映射
当文件支持存在放wwwroot
这个文件夹的时候,可以使用静态文件中间件的重载来映射其他文件夹,注释掉上一步的代码,将Startup.Configure
修改如下:
1 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) |
在项目根目录创建file
文件夹,在里面创建个file_page.html
文件,随便写点东西,运行项目,访问https://localhost:5001/file_page.html
,可以看到静态页内容。注意,如果出现同名文件,则先注册的路径优先权更高,如果需要在访问指定文件夹有指定url地址,可以使用StaticFileOptions
对象的RequestPath
属性,假设这里的RequestPath="/myfiles"
,则说明要想访问file
文件夹的内容,路径前面得加上myfiles
,例如https://localhost:5001/myfiles/file_page.html
功能实现
有这样一个需求,接口里所有接口的路由都由api
开始,即/api/xxx
,静态文件放在默认的wwwroot
文件夹中,如果访问的地址不是接口,同时也找不到对应的静态文件,则重写到/index.html
页面,具体代码如下:
修改WeatherForecastController
,将原本的[Route("[controller]")]
修改为[Route("/api/[controller]")]
修改Startup.Configure
方法,代码如下:
1 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) |
运行项目,访问https://localhost:5001/api/WeatherForecast
,可以看到正常返回接口信息,访问https://localhost:5001/a/index.html
可以看到正常访问到/a/index.html
文件内容,访问https://localhost:5001/order/get
则会返回/index.html
文件内容