来源

这些HTML , CSS files, image files, 和JavaScript这些静态文件,是ASP.NET能够直接响应给客户端的。本文详述下ASP.NET和静态文件的关系。

Serving static files##

静态文件存储在项目的webroot下,webroot的位置可以通过project.json文件来配置。

"webroot": "wwwroot"

静态文件可以存储在任何位置,可以通过相对路径来获取。webroot下的静态文件可以通过http:///images/路径来直接获取。

为了能够提供静态文件,必须配置中间件来将静态文件添加到管道中。可以通过在Startup类中的Configre方法里调用UseStaticFiles扩展方法来实现。如下

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Add static files to the request pipeline.
app.UseStaticFiles();
...

如果你想提供webroot之外的静态文件,项目结构如下:

  • wwwroot

    • css
    • img
    • js
  • MyStaticFiles
    • test.png

为了使用户能够访问test.png文件,必须如下配置静态文件:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Add MyStaticFiles static files to the request pipeline.
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\Source\WebApplication1\src\WebApplication1\MyStaticFiles"),
RequestPath = new PathString("/StaticFiles")
});
...

这时如果用户访问http:///StaticFiles/test.png这个路径,就可以获得对应文件。

文件目录浏览##

默认情况下,该功能是不可用的。开启该功能,需要在Startup.Configure中调用UseDirectoryBrowser方法,如下

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Turn on directory browsing for the current directory.
app.UseDirectoryBrowser();
...

浏览项目的images文件夹,结果如下:

如果有个文件夹在webroot之外,但是需要用户可浏览。项目结构如下:

  • wwwroot

    • css
    • img
    • js
  • MyStaticFiles

为了使用户可浏览MyStaticFiles目录,需要如下配置

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Add the ability for the user to browse the MyStaticFiles directory.
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\Source\WebApplication1\src\WebApplication1\MyStaticFiles"),
RequestPath = new PathString("/StaticFiles")
});
...

这时,如果如果用户访问地址http:///StaticFiles,就能浏览MyStaticFiles文件夹中的文件。

Serving default files##

在用户没有输入完整的URI的情况下,为了提供给用户默认的文件,需要在Startup.Configure中调用UseDefaultFiles。但同事也必须调用UseStaticFiles方法,这是因为UseDefaultFiles是url重写,并不提供文件服务。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Serve the default file, if present.
app.UseDefaultFiles();
app.UseStaticFiles();
...

如果你调用了UseDefaultFiles方法,如果用户输入了某个文件的路径,中间件会按顺序搜索如下文件。如果找到了,文件就会返回,就如同用户输入了完整路径一样。

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

为了指定其他默认文件,需要实例化DefaultFilesOptions对象,并设置其参数DefaultFileNames列表. 然后调用UseDefaultFiles,并把需要实例化DefaultFilesOptions对象对象传给它。下例,移除了DefaultFileNames列表中的默认的文件,并把mydefault.html添加作为唯一的默认文件。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// 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();
...

此时,如果你浏览webroot中的文件夹,并携带文件名mydefault.html,该文件就可以获取,就如同用户输入了全路径。

但是如果你想设置的默认文件在webroot之外,你需要调用UseStaticFiles和UseDefaultFiles,并传给他们相对的参数值。然而更方便和推荐的方法是使用

UseFileServer方法。

使用UseFileServer方法##

除了UseStaticFiles, UseDefaultFiles和 UseDirectoryBrowser扩展方法,还有UseFileServer方法,该方法结合了上面三个方法的功能。

// Enable all static file middleware (serving of static files and default files) EXCEPT directory browsing.
app.UseFileServer();
// Enables all static file middleware (serving of static files, default files, and directory browsing).
app.UseFileServer(enableDirectoryBrowsing: true);

如同UseStaticFiles, UseDefaultFiles和UseDirectoryBrowser,如果想服务webroot之外的文件,需要实例化和配置一个“options”对象,并作为参数传给UseFileServer。比如,有如下结构

  • wwwroot

    • css
    • img
    • js
  • MyStaticFiles
    • test.png
    • default.html

如上结构,如果想提供静态文件,默认文件以及目录浏览功能,如下只需调用UseFileServer方法。

app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\Source\WebApplication1\src\WebApplication1\MyStaticFiles"),
RequestPath = new PathString("/StaticFiles"),
EnableDirectoryBrowsing = true
});

如上例,如果用户访问如下路径

  • http:///StaticFiles/test.png - MyStaticFiles/test.png 文件会提供给浏览器
  • http:///StaticFiles - 因为有默认文件default.html,该文件会提供给浏览器。如果不存在默认文件,浏览器会提供文件浏览(因为 FileServerOptions.EnableDirectoryBrowsing属性设置为了true).

文件类型##

ASP.NET静态文件中间件提供了接近400种已知的文件类型。如果用户尝试获取位置类型的文件,ASP.NET不会尝试提供服务。

假设如下目录

  • wwwroot

    • css
    • js
    • images
      • test.image

按如下配置

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Serve static files and allow directory browsing.
app.UseDirectoryBrowser();
app.UseStaticFiles();

如果访问http:///images这个目录,服务器会列出包括test.image的文件列表。但是如果尝试打开该文件,则会抛出错误。为了服务位置类型的文件,你需要将StaticFileOptions.ServeUnknownFileTypes熟悉nag设置为true并指定默认文件类型。如下

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Serve static files and allow directory browsing.
app.UseDirectoryBrowser();
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "image/png"
});

这是如果浏览器访问未知类型的文件,服务器会将他们作为image/png类型来对待。

目前为止,在处理为未知类型文件时,已经指定了默认文件类型。但是如果有多种未知文件类型呢。这就是FileExtensionContentTypeProvider类发挥作用的时候了。这个类内部有一个集合,来映射文件扩展名和MIME文件类型。为了自定义文件类型,只需实例化FileExtensionContentTypeProvider,并添加映射到FileExtensionContentTypeProvider.Mappings字典。如下例,添加了扩展.myapp到application/x-msdownload MIME类型。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
... // Allow directory browsing.
app.UseDirectoryBrowser(); // Set up custom content types - associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".myapp", "application/x-msdownload"); // Serve static files.
app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider }); ...

现在如果用户尝试浏览.myapp后缀名的文件,用户会被提示下载该文件。

IIS Considerations##

IIS有自己的静态文件处理模块,它是独立与上文提到的ASP.NET静态文件中间件的。ASP.NET模块是在IIS本地模块之前运行的。在ASP.NET Beta 7中,IIS host改变了运行方式,如果请求没有被ASP.NET所处理,将会返回404错误,而不是交给IIS自身模块来处理。为了运行IIS自身模块,需如下配置。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
... ...
// Enable the IIS native module to run after the ASP.NET middleware components.
// This call should be placed at the end of your Startup.Configure method so that
// it doesn't interfere with other middleware functionality.
app.RunIISPipeline();
}

最佳实践##

代码文件(包括C#和Razor文件)应该放在项目的webroot之外,这样能够很好的隔离。

总结##

In this article, you learned how the static files middleware component in ASP.NET 5 allows you to serve static files, enable directory browsing, and serve default files. You also saw how to work with content types that ASP.NET doesn’t recognize. Finally, the article explained some IIS considerations and presented some best practices for working with static files.

ASP.NET Core 1.0基础之静态文件处理的更多相关文章

  1. 15.ASP.NET Core 应用程序中的静态文件中间件

    在这篇文章中,我将向大家介绍,如何使用中间件组件来处理静态文件.这篇文章中,我们讨论下面几个问题: 在ASP.NET Core中,我们需要把静态文件存放在哪里? 在ASP.NET Core中 wwwr ...

  2. ASP.NET Core 1.0 基础与应用启动

    .NET Core http://dotnet.github.io/[https://github.com/dotnet/coreclr] ASP.NET Core 1.0 https://get.a ...

  3. ASP.NET Core 1.0基础之依赖注入

      来源https://docs.asp.net/en/latest/fundamentals/dependency-injection.html ASP.NET Core 1.0在设计上原生就支持和 ...

  4. ASP.NET Core 1.0 基础之配置

    来源https://docs.asp.net/en/latest/fundamentals/configuration.html ASP.NET Core 1.0支持不同的配置选项.应用配置数据可以是 ...

  5. ASP.NET Core 1.0基础之日志

    过年出去玩了一圈,回来继续翻译.前两天偷懒没有翻译,只是转了两篇C# 7计划中的新features,大家还是很支持的.现在继续完善这个系列. 来源https://docs.asp.net/en/lat ...

  6. ASP.NET Core 1.0基础之诊断

    来源https://docs.asp.net/en/latest/fundamentals/diagnostics.html ASP.NET Core 1.0包含了一些新的特性来辅助诊断问题.可以在S ...

  7. [小技巧]ASP.NET Core中如何预压缩静态文件

    原文地址:Pre-compressed static files with ASP.NET Core 作者:Gunnar Peipman 译者:Lamond Lu 译文:https://www.cnb ...

  8. Asp .Net core 2 学习笔记(3) —— 静态文件

    这个系列的初衷是便于自己总结与回顾,把笔记本上面的东西转移到这里,态度不由得谨慎许多,下面是我参考的资源: ASP.NET Core 中文文档目录 官方文档 记在这里的东西我会不断的完善丰满,对于文章 ...

  9. asp.net core 教程(七)-异常处理、静态文件

    Asp.Net Core-异常处理 Asp.Net Core-异常处理 在这一章,我们将讨论异常和错误处理.当 ASP.NET Core应用程序中发生错误时,您可以以各种不同的方式来处理.让我们来看看 ...

随机推荐

  1. Opencv 学习笔记之——鼠标,进度条操作

    Opencv中提供一个鼠标调用的函数,SetMouseCallback()函数,它配合一个回调函数来实现鼠标操作的功能.   首先看一下SetMouseCallback的函数原型: c++: void ...

  2. Linux 邮件服务器 之跟我一步一步来实现一个邮件系统【转】

    转自:http://tchuairen.blog.51cto.com/3848118/1686875/ 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法 ...

  3. 【Linux驱动学习】SD卡规范学习

    摘要: 学习SD卡的相关规范,包括定义,硬件特性,数据传输,命令系统等.不涉及代码. 文章针对Linux驱动开发而写,以助于理解SD卡驱动,不会涉及过多硬件内容. 纲要: 1. SD卡介绍 2. SD ...

  4. sphinx-python文档化

    概述 下文讲述使用sphinx自动生成reStructuredText python API文档的简单过程. 配置流程 安装依赖 $ pip install sphinx blurb python-d ...

  5. [ 总结 ] Linux 下文件描述符

    1.概述: 文件描述符是内核为了高效管理已被打开的文件所创建的索引.是一个非负整数,用于代指被打开的文件.所有通过I/O操作的系统调用都通过文件描述符. 文件描述符用以表明每一个被进程所打开的文件和s ...

  6. C# 连接和操作SQL SERVER数据库

    用C#sqlserver实现增删改查http://www.worlduc.com/blog2012.aspx?bid=730767 using System.Data;using System.Dat ...

  7. apt-get常用命令及工作原理

    https://blog.csdn.net/mosquito_zm/article/details/63684608

  8. ThinkPHP的静态化页面方法

    原来ThinkPHP自带了生成静态页的函数buildHtml,使用起来很方便!最新的手册里没写这个方法,向大家介绍一下.     protected function buildHtml($htmlf ...

  9. Android Studio查找功能(搜索功能)

    F3 向下查找关键字出现位置 Shift+F3 向上一个关键字出现位置 2.在当前工程内查找文本[Ctrl+Shift+F] 先会弹出一个对话框,直接点击[find],开始在整个工程内查找该字符串   ...

  10. Codeforces 855C - Helga Hufflepuff's Cup

    855C - Helga Hufflepuff's Cup 题意 要求构建一棵树,树上至多可以存在 \(x\) 个权值为 \(k\) 的重要点,且与重要点连边的点的权值必须小于 \(k\),问有多少种 ...