ASP.NET Core 静态文件
静态文件(HTML,CSS,图片和Javascript之类的资源)会被ASP.NET Core应用直接提供给客户端。
静态文件通常位于网站根目录(web root) <content-root>/wwwroot文件夹下。通常会把项目的当前目录设置为Content root,这样项目的web root就可以在开发阶段被明确。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseContentRoot(Directory.GetCurrentDirectory()) //设置当前目录 .UseStartup<Startup>();
静态文件能够被保存在网站根目录下的任意文件夹内,并通过相对根的路径来访问。使用vs创建一个默认的Web应用程序时,在wwwroot目录下会生成几个文件夹:css,images,js。如果压迫访问images目录下的图片:
http://<app>/iamges/filename
https://localhost:44303/iamges/filename
要想使用静态文件服务,必须配置中间件,把静态文件中间件加入到管道。静态文件一般会默认配置,在Configure方法中调用app.UseStaticFiles()。
app.UseStaticFiles() 使得web root(默认为wwwroot)下的文件可以被访问。同时可以通过UseStaticFiles方法将其他目录下的内容也可以向外提供:
假如wwwroot外面有一个MyStaticFiles文件夹,要访问文件夹里面的资源test.png:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")), //用于定位资源的文件系统 RequestPath = new PathString("/StaticFiles") //请求地址 }); }
可以通过访问
http://<app>/StaticFiles/test.png
https://localhost:44303/StaticFiles/test.png
1.静态文件授权
静态文件组件默认不提供授权检查。任何通过静态文件中间件访问的文件都是公开的。要想给文件授权,可以将文件保存在wwwroot之外,并将目录设置为可被静态文件中间件能够访问,同时通过一个controller action来访问文件,在action中授权后返回FileResult。
2.目录浏览
目录浏览允许网站用户看到指定目录下的目录和文件列表。基于安全考虑,默认情况下是禁止目录访问功能。在Startup.Configure中调用UseDirectoryBrowser扩展方法可以开启网络应用目录浏览:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseDirectoryBrowser(new DirectoryBrowserOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(),@"wwwroot\images")), RequestPath = new PathString("/MyImages") //如果不指定RequestPath,会将PhysicalFileProvider中的路径参数作为默认文件夹,替换掉wwwroot
}); }
然后在Startup.CongigureServices中调用AddDirectoryBrowser扩展方法。
这样就可以通过访问http://<app>/MyImages浏览wwwroot/images文件夹中的目录,但是不能访问文件:
要想访问具体文件需要调用UseStaticFiles配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")), //用于定位资源的文件系统 RequestPath = new PathString("/MyImages") }); app.UseDirectoryBrowser(new DirectoryBrowserOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(),@"wwwroot\images")), RequestPath = new PathString("/MyImages") }); }
3.默认文件
设置默认首页能给站点的访问者提供一个起始页,在Startup.Configure中调用UseDefaFiles扩展方法:
app.UseDefaultFiles(options);
app.UseStaticFiles();
UseDefaultFiles必须在UseStaticFiles之前调用。UseDefaultFiles只是重写了URL,而不是真的提供了一个这样的文件,浏览器URL将继续显示用户输入的URL。所以必须开启静态文件中间件。而且默认文件必须放在静态文件中间件可以访问得到的地方,默认是wwwroot中。
通过UseDefaultFiles,请求文件夹的时候检索以下文件:
default.htm
default.html
index.htm
index.html
也可以使用UseDefaultFiles将默认页面改为其他页面:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); DefaultFilesOptions options = new DefaultFilesOptions(); options.DefaultFileNames.Clear(); options.DefaultFileNames.Add("mydefault.html"); app.UseDefaultFiles(options); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
4.UseFileServer
UseFileServer集合了UseStaticFiles,UseDefaultFiles,UseDirectoryBrowser。
调用app.UseFileServer(); 请用了静态文件和默认文件,但不允许直接访问目录。需要调用app.UseFileServer(enableDirectoryBrowsing:true); 才能启用目录浏览功能。
如果想要访问wwwroot以外的文件,需要配置一个FileServerOptions对象
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
app.UseStaticFiles();//如果不调用,将不会启动默认功能。 app.UseFileServer(new FileServerOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")), RequestPath = new PathString("/StaticFiles"), EnableDirectoryBrowsing = true }); }
注意,如果将enableDirectoryBrowsing设置为true,需要在ConfigureServices中调用services.AddDirectoryBrowser();
如果默认文件夹下有默认页面,将显示默认页面,而不是目录列表。
5.FileExtensionContentTypeProvider
FileExtensionContentTypeProvider类包含一个将文件扩展名映射到MIME内容类型的集合。
例如:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var provider = new FileExtensionContentTypeProvider(); provider.Mappings[".htm3"] = "text/html"; provider.Mappings["images"] = "iamge/png"; provider.Mappings.Remove(".mp4"); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider( Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")), RequestPath = new PathString("/StaticFiles"), ContentTypeProvider = provider }); }
更多MIME类型可以访问:http://www.iana.org/assignments/media-types/media-types.xhtml
6.非标准的内容类型
如果用户请求了一个未知的文件类型,静态文件中间件将会返回HTTP 404响应。如果启用目录浏览,则该文件的链接将会被显示,但RUI会返回一个HTTP404错误。
使用UseStaticFiles方法可以将未知类型作为指定类型处理:
app.UseStaticFiles(new StaticFileOptions() { ServeUnknownFileTypes = true, DefaultContentType = "application/x-msdownload" });
对于未识别的,默认为application/x-msdownload,浏览器将会下载这些文件。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析