何谓静态文件,文件系统上的文件, css, javascript , image. html 这些都属于静态文件,
.net core web app 默认是不处理文件请求的. 我们来做一个实验
,首先我们 得在项目根目录创建一个根文件夹, 名称为wwwroot
创建好后图标变成了
添加一个images的文件夹,放入一张图片
运行项目,我们输入http://localhost:50771/images/4.jpg, 效果
中间件正常的工作,只是没有任何中间件处理处理响应,这正是验证了我们之前说的, .net core 默认不处理静态文件请求
这时我们要手动添加 处理静态文件请求的中间件
修改startup 里的configure方法为
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //静态文件中间件 app.UseStaticFiles(); app.Run(async (context) => { //在这里产生响应 context.Response.Headers["Content-Type"] = "application/json"; await context.Response.WriteAsync("hello word"); }); }
这样做完之后,当.net core web app收到请求静态文件的请求时, 在app.useStaticFiles();这一行就response了, 下面的app.run不会再response hello word
然后我们尝试访问一下刚才的图片
成功了, 然后我们再添加一个主页 index.html试试 在body里写上hello word from index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <h1 >hello word from index.html</h1> </body> </html>
然后我们运行起来看到的效果是
这个hello word来自 app.run 里面的 resopnse. 不是来自index.html
这是因为现在还没有开启 默认名中间件, 默认名中间件应该加在 staticFiles中间前面,否则不能正常使用.
//默认名中间件 app.UseDefaultFiles(); //静态文件中间件 app.UseStaticFiles();
默认的主页支持
index.html
index.htm
defualt.html
defualt.htm
我们运行起来看一下效果
成功了,但是如果想自定义默认名称怎么办. 比如我们要设置默认的主页为foo.html
创建一个foo.html 在body里写 hello word from foo.html
.net core web app有很多中间件都支持一个options的参数 我们要使用defaultFilesOpthin 来添加foo.html为默认名.
//默认名中间件 DefaultFilesOptions dfo = new DefaultFilesOptions(); dfo.DefaultFileNames.Clear(); dfo.DefaultFileNames.Add("foo.html"); app.UseDefaultFiles(dfo); //静态文件中间件 app.UseStaticFiles();
运行起来看到的效果
成功了. 刚才讲的staticFles 和 DefaultFiles 两个中间件的功能还可以用FileServe 中间件来实现
//使用fileServer代替 staticFiles 和defaultFiles FileServerOptions fso = new FileServerOptions(); fso.DefaultFilesOptions.DefaultFileNames.Clear(); fso.DefaultFilesOptions.DefaultFileNames.Add("foo.html"); app.UseFileServer();
效果 是一样的.