ASP.NET|ASP.NET Core中的静态文件介绍

静态文件(HTML,CSS,图片和Javascript之类的资源)会被ASP.NET Core应用直接提供给客户端。
静态文件通常位于网站根目录(web root) /wwwroot文件夹下。通常会把项目的当前目录设置为Content root,这样项目的web root就可以在开发阶段被明确。

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>WebHost.CreateDefaultBuilder(args).UseContentRoot(Directory.GetCurrentDirectory()) //设置当前目录.UseStartup();

静态文件能够被保存在网站根目录下的任意文件夹内,并通过相对根的路径来访问。使用vs创建一个默认的Web应用程序时,在wwwroot目录下会生成几个文件夹:css,images,js。如果压迫访问images目录下的图片:
http:///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:///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:///MyImages浏览wwwroot/images文件夹中的目录,但是不能访问文件:
ASP.NET|ASP.NET Core中的静态文件介绍
文章图片

要想访问具体文件需要调用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,浏览器将会下载这些文件。
【ASP.NET|ASP.NET Core中的静态文件介绍】到此这篇关于ASP.NET Core静态文件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读