原文:Working with Static Files

作者:Rick Anderson

翻译:刘怡(AlexLEWIS)

校对:谢炀(kiler398)许登洋(Seay)孟帅洋(书缘)

静态文件(static files),诸如 HTML、CSS、图片和 JavaScript 之类的资源会被 ASP.NET Core 应用直接提供给客户端。

查看或下载样式代码

章节:

静态文件服务

静态文件通常位于 web root<content-root>/wwwroot)文件夹下。更多有关 Content root 或 Web root 的信息请访问 intro 。你通常会把项目的当前目录设置为 Content root,这样项目的 web root 就可以在开发阶段被明确。

public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory()) //手工高亮
.UseIISIntegration()
.UseStartup<Startup>()
.Build(); host.Run();
}

静态文件能够被保存在网站根目录下的任意文件夹内,并通过相对根的路径来访问。比方说,当你通过 Visual Studio 创建一个默认的 Web 应用程序项目,在 wwwroot 目录下会多出几个文件夹:cssimages 以及 js 文件夹。形如下例的 URL 能够直接访问 images 目录下的图片:

  • http://<app>/images/<imageFileName>
  • http://localhost:9189/images/banner3.svg

为了能够启用静态文件服务,你必须配置中间件(middleware),把静态文件中间件加入到管道内。静态文件中间件能够通过下述方法来配置:在你的项目中增加 Microsoft.AspNetCore.StaticFiles 包依赖,然后从 Startup.Configure 调用 UseStaticFiles 扩展方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles(); //手工高亮
}

app.UseStaticFiles(); 使得 web root(默认为 wwwroot)下的文件可以被访问。随后我将展示如何通过使用 UseStaticFiles 将其他目录下的内容也向外提供服务。

你必须在 project.json 文件中包含 “Microsoft.AspNetCore.StaticFiles”。

注意

web root 的默认目录是 wwwroot,但你可以通过 UseWebRoot 来设置 web root 。具体可参考 intro

假设你有一个有层次结构的项目,你希望其中静态文件的位于 web root 的外部,比如:

  • wwwroot

    • css
    • images
    • ...
  • MyStaticFiles

    • test.png

对于访问 test.png 的请求,可以如此配置静态文件中间件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() //手工高亮
{ //手工高亮
FileProvider = new PhysicalFileProvider( //手工高亮
Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")), //手工高亮
RequestPath = new PathString("/StaticFiles") //手工高亮
}); //手工高亮
}

在请求 http://<app>/StaticFiles/test.png 时,就能访问到 test.png 文件。

静态文件授权

静态文件模块并 提供授权检查。任何通过该模块提供访问的文件,包括位于 wwwroot 下的文件都是公开的。为了给文件提供授权:

  • 将文件保存在 wwwroot 之外并将目录设置为可被静态文件中间件访问到,同时——
  • 通过一个控制器的 Action 来访问它们,通过授权后返回 FileResult

允许直接浏览目录

目录浏览允许网站用户看到指定目录下的目录和文件列表。基于安全考虑,默认情况下是禁用目录访问功能的(参考 注意事项 )。在 Startup.Configure 中调用 UseDirectoryBrowser 扩展方法可以开启网络应用目录浏览:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles(); // For the wwwroot folder 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")
});
}

并且通过从 Startup.ConfigureServices 调用 AddDirectoryBrowser 扩展方法来增加所需服务。

public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
}

这段代码允许在访问 http://<app>/MyImages 时可浏览 wwwroot/images 文件夹的目录,其中包括该文件夹下的每一个文件与文件夹:

查看关于开放访问目录时的安全隐患 注意事项 一节。

注意两个 app.UseStaticFiles 调用。第一个调用请求 wwwroot 文件夹下的 CSS、图片和 JavaScript,第二个调用通过 http://<app>/MyImages 请求浏览 wwwroot/images 文件夹的目录

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles(); // For the wwwroot folder //手工高亮 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")
});
}

默认文档服务

设置默认首页能给你的站点的每个访问者提供一个起始页。为使站点能提供默认页,避免用户输入完整 URI,须在 Startup.Configure 中调用 UseDefaultFiles 扩展方法:

public void Configure(IApplicationBuilder app)
{
app.UseDefaultFiles(); //手工高亮
app.UseStaticFiles();
}

注意

UseDefaultFiles 必须在 UseStaticFiles 之前调用。UseDefaultFiles 只是重写了 URL,而不是真的提供了这样一个文件。你必须开启静态文件中间件(UseStaticFiles)来提供这个文件。

通过 UseDefaultFiles,请求文件夹的时候将检索以下文件:

  • default.htm
  • default.html
  • index.htm
  • index.html

上述列表中第一个被找到的文件将返回给用户(作为该完整 URI 的请求的应答,而此时浏览器 URL 将继续显示用户输入的 URI)。

下述代码展示如何将默认文件名改为 mydefault.html

public void Configure(IApplicationBuilder app)
{
// Serve my app-specific default file, if present.
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mydefault.html");
app.UseDefaultFiles(options);
app.UseStaticFiles();
}

UseFileServer

UseFileServer 包含了 UseStaticFilesUseDefaultFilesUseDirectoryBrowser 的功能。

下面的代码启用了静态文件和默认文件,但不允许直接访问目录:

app.UseFileServer();

下面的代码启用了静态文件、默认文件和目录浏览功能:

app.UseFileServer(enableDirectoryBrowsing: true);

查看直接提供目录访问时的安全风险注意事项。作为一个集合了 UseStaticFilesUseDefaultFilesUseDirectoryBrowser 方法于一体的方法,如果你希望提供 web root 之外存在的文件,你要实例化并配置一个 FileServerOptions 对象传递给 UseFileServer 的参数。比方说在你的应用中有如下层次的目录:

  • wwwroot

    • css
    • images
    • ...
  • MyStaticFiles

    • test.png
    • default.html

使用上面这个层次结构的示例,你可能希望启用静态文件、默认文件以及浏览 MyStaticFiles 目录。下面的代码片段演示了调用一次 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 //手工高亮
}); //手工高亮
}

如果在你从 Startup.ConfigureServices 请求调用 AddDirectoryBrowser 扩展方法时将 enableDirectoryBrowsing 置为 true,那么:

public void ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
}

使用的文件层次结构:

URI Response
http://<app>/StaticFiles/test.png StaticFiles/test.png
http://<app>/StaticFiles MyStaticFiles/default.html

如果在 MyStaticFiles 目录下没有默认命名的文件,则 http://<app>/StaticFiles 将返回目录列表,其中包含可供点击的链接:

注意

UseDefaultFilesUseDirectoryBrowser 将会把末尾不带斜杠的 URL http://<app>/StaticFiles 重新定向到 http://<app>/StaticFiles/ (末尾增加了一个斜杠)。如果末尾不带斜杠,文档内相对 URL 会出错。

FileExtensionContentTypeProvider

FileExtensionContentTypeProvider 类内包含一个将文件扩展名映射到 MIME 内容类型的集合。在下面的例子中,多个文件扩展名注册为已知的 MIME 类型,“.rtf”被替换,“.mp4”被移除。

public void Configure(IApplicationBuilder app)
{
// Set up custom content types -associating file extension to MIME type //手工高亮
var provider = new FileExtensionContentTypeProvider(); //手工高亮
// Add new mappings //手工高亮
provider.Mappings[".myapp"] = "application/x-msdownload"; //手工高亮
provider.Mappings[".htm3"] = "text/html"; //手工高亮
provider.Mappings[".image"] = "image/png"; //手工高亮
// Replace an existing mapping //手工高亮
provider.Mappings[".rtf"] = "application/x-msdownload"; //手工高亮
// Remove MP4 videos. //手工高亮
provider.Mappings.Remove(".mp4"); //手工高亮 app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages"),
ContentTypeProvider = provider //手工高亮
}); app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images")),
RequestPath = new PathString("/MyImages")
});
}

查看 MIME 内容类型

非标准的内容类型

ASP.NET 静态文件中间件能够支持超过 400 种已知文件内容类型。如果用户请求一个未知的文件类型,静态文件中间件将返回 HTTP 404(未找到)响应。如果启用目录浏览,该文件的链接将会被显示,但 URI 会返回一个 HTTP 404 错误。

下方代码把不能识别的类型和文件作为图片处理。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "image/png"
});
}

根据上面的代码,未知内容类型的文件请求将返回一张图片。

警告

开启 ServeUnknownFileTypes 存在安全风险,请打消这个念头。 FileExtensionContentTypeProvider (下文将解释)提供了更安全的非标准扩展替代。

注意事项

警告

UseDirectoryBrowserUseStaticFiles 可能会泄密。我们推荐你 不要 在生产环境开启目录浏览。要小心哪些被你开启了 UseStaticFilesUseDirectoryBrowser 的目录(使得其子目录都可被访问)。我们建议将公开内容放在诸如 <content root>/wwwroot 这样的目录中,远离应用程序视图、配置文件等。

  • 使用 UseDirectoryBrowserUseStaticFiles 暴露的文件的 URL 是否区分大小写以及字符限制受制于底层文件系统。比方说 Windows 是不区分大小写的,但 macOS 和 Linux 则区分大小写。

  • 托管于 IIS 的 ASP.NET Core 应用程序使用 ASP.NET Core 模块向应用程序转发所有请求,包括静态文件。IIS 静态文件处理程序(IIS Static File Handler)不会被使用,因为在 ASP.NET Core 模块处理之前它没有任何机会来处理请求。

  • 以下步骤可移除 IIS 静态文件处理程序(在服务器层级或网站层级上):

    • 导航到 模块 功能
    • 从列表中选中 StaticFileModule
    • 操作 侧边栏中点击 删除

警告

如果 IIS 静态文件处理程序开启 并且 ASP.NET Core 模块(ANCM)没有被正确配置(比方说 web.config 没有部署),(也能)将会提供静态文件。

  • 代码文件(包括 C# 和 Razor)应该放在应用程序项目的 web root (默认为 wwwroot)之外的地方。这将确保您创建的应用程序能明确隔离客户端侧和服务器侧源代码,此举能防止服务器侧的代码被泄露。

扩展资源

返回目录

ASP.NET Core 中文文档 第三章 原理(3)静态文件处理的更多相关文章

  1. ASP.NET Core 中文文档 第三章 原理(6)全球化与本地化

    原文:Globalization and localization 作者:Rick Anderson.Damien Bowden.Bart Calixto.Nadeem Afana 翻译:谢炀(Kil ...

  2. ASP.NET Core 中文文档 第三章 原理(1)应用程序启动

    原文:Application Startup 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:谢炀(kiler398).许登洋(Seay) ASP.NET Core 为你的应用程 ...

  3. ASP.NET Core 中文文档 第三章 原理(13)管理应用程序状态

    原文:Managing Application State 作者:Steve Smith 翻译:姚阿勇(Dr.Yao) 校对:高嵩 在 ASP.NET Core 中,有多种途径可以对应用程序的状态进行 ...

  4. ASP.NET Core 中文文档 第三章 原理(2)中间件

    原文:Middleware 作者:Steve Smith.Rick Anderson 翻译:刘怡(AlexLEWIS) 校对:许登洋(Seay) 章节: 什么是中间件 用 IApplicationBu ...

  5. ASP.NET Core 中文文档 第三章 原理(10)依赖注入

    原文:Dependency Injection 作者:Steve Smith 翻译:刘浩杨 校对:许登洋(Seay).高嵩 ASP.NET Core 的底层设计支持和使用依赖注入.ASP.NET Co ...

  6. ASP.NET Core 中文文档 第三章 原理(11)在多个环境中工作

    原文: Working with Multiple Environments 作者: Steve Smith 翻译: 刘浩杨 校对: 孟帅洋(书缘) ASP.NET Core 介绍了支持在多个环境中管 ...

  7. ASP.NET Core 中文文档 第三章 原理(17)为你的服务器选择合适版本的.NET框架

    原文:Choosing the Right .NET For You on the Server 作者:Daniel Roth 翻译:王健 校对:谢炀(Kiler).何镇汐.许登洋(Seay).孟帅洋 ...

  8. ASP.NET Core 中文文档 第三章 原理(7)配置

    原文:Configuration 作者:Steve Smith.Daniel Roth 翻译:刘怡(AlexLEWIS) 校对:孟帅洋(书缘) ASP.NET Core 支持多种配置选项.应用程序配置 ...

  9. ASP.NET Core 中文文档 第三章 原理(8)日志

    原文:Logging 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:何镇汐.许登洋(Seay) ASP.NET Core 内建支持日志,也允许开发人员轻松切换为他们想用的其他日 ...

随机推荐

  1. Docker 第一篇--初识docker

    已经多年不写博客, 看完<晓松奇谈>最后一期猛然觉醒, 决定仔细梳理下自己这几年的知识脉络. 既然决定写, 那么首先就从最近2年热门的开源项目Docker开始.Docker 这两年在国内很 ...

  2. .Net多线程编程—任务Task

    1 System.Threading.Tasks.Task简介 一个Task表示一个异步操作,Task的创建和执行是独立的. 只读属性: 返回值 名称 说明 object AsyncState 表示在 ...

  3. HTML DOM 对象

    本篇主要介绍HTML DOM 对象:Document.Element.Attr.Event等4个对象. 目录 1. Document 对象:表示文档树的根节点,大部分属性和方法都是对元素进行操作. 2 ...

  4. HTML5 localStorage本地存储

    介绍 localStorage(本地存储)的使用方式.包括对存储对象的添加.修改.删除.事件触发等操作. 目录 1. 介绍 1.1 说明 1.2 特点 1.3 浏览器最小版本支持 1.4 适合场景 2 ...

  5. [APUE]标准IO库(下)

    一.标准IO的效率 对比以下四个程序的用户CPU.系统CPU与时钟时间对比 程序1:系统IO 程序2:标准IO getc版本 程序3:标准IO fgets版本 结果: [注:该表截取自APUE,上表中 ...

  6. HTML骨架结构

    前面的话   一个完整的HTML文档必须包含3个部分:文档声明.文档头部和文档主体.而正是它们构成了HTML的骨架结构.前面已经分别介绍过文档声明和文档头部,本文将详细介绍构成HTML骨架结构的基础元 ...

  7. Hive安装配置指北(含Hive Metastore详解)

    个人主页: http://www.linbingdong.com 本文介绍Hive安装配置的整个过程,包括MySQL.Hive及Metastore的安装配置,并分析了Metastore三种配置方式的区 ...

  8. mybatis plugins实现项目【全局】读写分离

    在之前的文章中讲述过数据库主从同步和通过注解来为部分方法切换数据源实现读写分离 注解实现读写分离: http://www.cnblogs.com/xiaochangwei/p/4961807.html ...

  9. C#中如何调整图像大小

    在本篇文章中,我将介绍如何在C#中来调整你想要的图像大小.要实现这一目标,我们可以采取以下几个步骤: 1.首先要获取你想要调整大小的图像: string path = Server.MapPath(& ...

  10. spring的BeanFactory加载过程

    ApplicationContext spring = new ClassPathXmlApplicationContext("classpath*:spring/applicationCo ...