ASP.NET Core 中文文档 第三章 原理(3)静态文件处理
原文: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 目录下会多出几个文件夹:css、images 以及 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 包含了 UseStaticFiles 、UseDefaultFiles 和 UseDirectoryBrowser 的功能。
下面的代码启用了静态文件和默认文件,但不允许直接访问目录:
app.UseFileServer();
下面的代码启用了静态文件、默认文件和目录浏览功能:
app.UseFileServer(enableDirectoryBrowsing: true);
查看直接提供目录访问时的安全风险注意事项。作为一个集合了 UseStaticFiles、UseDefaultFiles 和 UseDirectoryBrowser 方法于一体的方法,如果你希望提供 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 将返回目录列表,其中包含可供点击的链接:
注意
UseDefaultFiles和UseDirectoryBrowser将会把末尾不带斜杠的 URLhttp://<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 (下文将解释)提供了更安全的非标准扩展替代。
注意事项
警告
UseDirectoryBrowser和UseStaticFiles可能会泄密。我们推荐你 不要 在生产环境开启目录浏览。要小心哪些被你开启了UseStaticFiles或UseDirectoryBrowser的目录(使得其子目录都可被访问)。我们建议将公开内容放在诸如<content root>/wwwroot这样的目录中,远离应用程序视图、配置文件等。
使用
UseDirectoryBrowser和UseStaticFiles暴露的文件的 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)静态文件处理的更多相关文章
- ASP.NET Core 中文文档 第三章 原理(6)全球化与本地化
原文:Globalization and localization 作者:Rick Anderson.Damien Bowden.Bart Calixto.Nadeem Afana 翻译:谢炀(Kil ...
- ASP.NET Core 中文文档 第三章 原理(1)应用程序启动
原文:Application Startup 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:谢炀(kiler398).许登洋(Seay) ASP.NET Core 为你的应用程 ...
- ASP.NET Core 中文文档 第三章 原理(13)管理应用程序状态
原文:Managing Application State 作者:Steve Smith 翻译:姚阿勇(Dr.Yao) 校对:高嵩 在 ASP.NET Core 中,有多种途径可以对应用程序的状态进行 ...
- ASP.NET Core 中文文档 第三章 原理(2)中间件
原文:Middleware 作者:Steve Smith.Rick Anderson 翻译:刘怡(AlexLEWIS) 校对:许登洋(Seay) 章节: 什么是中间件 用 IApplicationBu ...
- ASP.NET Core 中文文档 第三章 原理(10)依赖注入
原文:Dependency Injection 作者:Steve Smith 翻译:刘浩杨 校对:许登洋(Seay).高嵩 ASP.NET Core 的底层设计支持和使用依赖注入.ASP.NET Co ...
- ASP.NET Core 中文文档 第三章 原理(11)在多个环境中工作
原文: Working with Multiple Environments 作者: Steve Smith 翻译: 刘浩杨 校对: 孟帅洋(书缘) ASP.NET Core 介绍了支持在多个环境中管 ...
- ASP.NET Core 中文文档 第三章 原理(17)为你的服务器选择合适版本的.NET框架
原文:Choosing the Right .NET For You on the Server 作者:Daniel Roth 翻译:王健 校对:谢炀(Kiler).何镇汐.许登洋(Seay).孟帅洋 ...
- ASP.NET Core 中文文档 第三章 原理(7)配置
原文:Configuration 作者:Steve Smith.Daniel Roth 翻译:刘怡(AlexLEWIS) 校对:孟帅洋(书缘) ASP.NET Core 支持多种配置选项.应用程序配置 ...
- ASP.NET Core 中文文档 第三章 原理(8)日志
原文:Logging 作者:Steve Smith 翻译:刘怡(AlexLEWIS) 校对:何镇汐.许登洋(Seay) ASP.NET Core 内建支持日志,也允许开发人员轻松切换为他们想用的其他日 ...
随机推荐
- 让 windows 下的命令行程序 cmd.exe 用起来更顺手
在 Windows 下使用 Larave 框架做开发,从 Composer 到 artisan 总是避免不了和 cmd.exe 打交道,系统默认的命令行界面却是不怎么好看,且每行显示的字符数是做了限制 ...
- kindeditor4整合SyntaxHighlighter,让代码亮起来
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代码高亮,因为SyntaxHighlighter的应用非常广泛,所以将kindeditor默认的prettify替换 ...
- 【开源】分享2011-2015年全国城市历史天气数据库【Sqlite+C#访问程序】
由于个人研究需要,需要采集天气历史数据,前一篇文章:C#+HtmlAgilityPack+XPath带你采集数据(以采集天气数据为例子),介绍了基本的采集思路和核心代码,经过1个星期的采集,历史数据库 ...
- iOS开发之ReactiveCocoa下的MVVM(干货分享)
最近工作比较忙,但还是出来更新博客了,今天给大家分享一些ReactiveCocoa以及MVVM的一些东西,干活还是比较足的.在之前发表过一篇博文,名字叫做<iOS开发之浅谈MVVM的架构设计与团 ...
- Spark踩坑记——初试
[TOC] Spark简介 整体认识 Apache Spark是一个围绕速度.易用性和复杂分析构建的大数据处理框架.最初在2009年由加州大学伯克利分校的AMPLab开发,并于2010年成为Apach ...
- 代码的坏味道(21)——中间人(Middle Man)
坏味道--中间人(Middle Man) 特征 如果一个类的作用仅仅是指向另一个类的委托,为什么要存在呢? 问题原因 对象的基本特征之一就是封装:对外部世界隐藏其内部细节.封装往往伴随委托.但是人们可 ...
- 基于window7+caffe实现图像艺术风格转换style-transfer
这个是在去年微博里面非常流行的,在git_hub上的代码是https://github.com/fzliu/style-transfer 比如这是梵高的画 这是你自己的照片 然后你想生成这样 怎么实现 ...
- 验证管理员权限(C#)
参考页面: http://www.yuanjiaocheng.net/webapi/test-webapi.html http://www.yuanjiaocheng.net/webapi/web-a ...
- PHP static静态属性和静态方法
这里分析了php面向对象中static静态属性和静态方法的调用.关于它们的调用(能不能调用,怎么样调用),需要弄明白了他们在内存中存放位置,这样就非常容易理解了.静态属性.方法(包括静态与非静态)在内 ...
- 文档对象模型DOM通俗讲解
转自:http://www.jb51.net/article/42671.htm 在开始之前先说一点,DOM是非常容易理解的,但是大家说的太官方,让人很是难于理解,我们就用非常简单的语言翻译一遍.加深 ...