静态文件 (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, 浏览器将会下载这些文件.
来源: https://www.cnblogs.com/afei-24/p/10753222.html