来源

这些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. SSM初步整合一

    SSM(spring+springmvc+mybatis)初步整合一配置步骤: 步骤一.导入所需jar包 步骤二 .配置web.xml文件 <?xml version="1.0&quo ...

  2. csrf_execmp

    参考;https://www.cnblogs.com/zhaof/p/6281482.html 全局: 中间件 django.middleware.csrf.CsrfViewMiddleware 局部 ...

  3. linux===linux在线模拟器汇总

    jslinux: http://bellard.org/jslinux/ 一个叫Fabrice Bellard的工程师使用 JavaScript 在浏览器上模拟出了一个 Linux 系统.没有图形化界 ...

  4. Oracle rman 全备份的一个小例子

    run{  allocate channel d1 type disk;  backup database format='/u01/backup/%T_%d_%s.bak';  sql 'alter ...

  5. 【洛谷】xht模拟赛 题解

    前言 大家期待已久并没有的题解终于来啦~ 这次的T1和HAOI2016撞题了...深表歉意...表示自己真的不知情... 天下的水题总是水得相似,神题各有各的神法.--<安娜·卡列妮娜> ...

  6. shell 通过ANSI转换颜色

    格式: echo -e "\033[字背景颜色;字体颜色m字符串\033[控制码" 如果单纯显示字体颜色可以固定控制码位0m. 格式: echo -e "\033[字背景 ...

  7. SQL--面试题

    表A字段如下 month  name income 月份   人员 收入 1      a    1000 2      a    2000 3      a    3000要求用一个SQL语句(注意 ...

  8. django static文件的引入方式(转)

    1. 在django project中创建 static文件夹 2.settings.py中配置要在 STATIC_URL = '/static/'  下边 STATICFILES_DIRS = [ ...

  9. 执行程序(例如UltraEdit)在WIN7下添加到右键菜单

    把下面提供的代码复制到记事本,保存为注册表文件(*.reg),右键合并即可.注意把最后一行换成你自己的路径. Windows Registry Editor Version 5.00 [HKEY_CL ...

  10. POJ 1240 Pre-Post-erous! && East Central North America 2002 (由前序后序遍历序列推出M叉树的种类)

    题目链接:http://poj.org/problem?id=1240 本文链接:http://www.cnblogs.com/Ash-ly/p/5482520.html 题意: 通过一棵二叉树的中序 ...