来源

这些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. 【HDU3853】LOOPS [期望DP]

    LOOPS Time Limit: 5 Sec  Memory Limit: 64 MB[Submit][Status][Discuss] Description Akemi Homura is a ...

  2. codeforces 854 problem E

    E. Boredom Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time t ...

  3. Kali 1.0 / 2.0 安装中文输入法(谷歌pinyin + 其他)

    1.kali默认是没有中午输入法的,需要自己安装一下 2.首先我们先获取root权限 dnt@HackerKali:~$ su密码: 3.安装中文输入法(apt-get 指令不会的同学可以学习一下基础 ...

  4. python imageai 对象检测、对象识别

    imageai库里面提供了目标识别,其实也可以说是目标检测,和现在很多的收集一样就是物体识别.他可以帮你识别出各种各样生活中遇见的事物.比如猫.狗.车.马.人.电脑.收集等等. 感觉imageai有点 ...

  5. 正则表达式解析基本json

    var str='{"state": "SUCCESS","original": "C:\Users\liuhao_a\Deskt ...

  6. Oracle rman 各种恢复

    --恢复整个数据库run {shutdown immediate;startup mount;restore database;recover database;alter database open ...

  7. Oracle基础 12 对象 objects 同义词/序列/试图/索引

    --创建同义词create public synonym employees for hr.employees;  --公共同义词需要 create public synonym 权限 表的所有用户授 ...

  8. [ 总结 ] web server iptables 简单配置

    [root@server ~]# iptables -F [root@server ~]# iptables -X [root@server ~]# iptables -A INPUT -m stat ...

  9. STL模板整理 pair

    pair pair是一种模板类型,其中包含两个数据值,两个数据的类型可以不同.如果一个函数有两个返回值的话,如果是相同类型,就可以用数组返回,如果是不同类型,就可以自己写个struct ,但为了方便就 ...

  10. CF 990A. Commentary Boxes【数学/模拟】

    [链接]:CF [题意]:对于一个数n,每次加一的代价是a,每次减一的代价是b,求被m整除时的最小代价. [分析]:分情况讨论,自己多举几个栗子. [代码]: #include<cstdio&g ...