一、介绍

静态文件(static files),诸如 html、css、图片和 javascript 之类的资源会被 asp.net core 应用直接提供给客户端。

在介绍静态文件中间件之前,先介绍 contentroot和webroot概念。

contentroot:指web的项目的文件夹,包括bin和webroot文件夹。

webroot:一般指contentroot路径下的wwwroot文件夹。

介绍这个两个概念是因为静态资源文件一般存放在webroot路径下,也就是wwwroot。下面为这两个路径的配置,如下所示:

public static void main(string[] args)
  {var host = new webhostbuilder()
      .usekestrel()
      .usestartup<startup>()
      .usecontentroot(directory.getcurrentdirectory())
      .usewebroot(directory.getcurrentdirectory() + @"\wwwroot\")
      .useenvironment(environmentname.development)
      .build();
   host.run();
  }

上面的代码将contentroot路径和webroot路径都配置了,其实只需配置contentroot路径,webroot默认为contentroot路径下的wwwroot文件夹路径。

在了解静态文件中间件前,还需要了解http中关于静态文件缓存的机制。跟静态文件相关的http头部主要有etag和if-none-match。

下面为访问静态文件服务器端和客户端的流程:

1、客户端第一次向客户端请求一个静态文件。

2、服务器收到客户端访问静态文件的请求,服务器端会根据静态文件最后的修改时间和文件内容的长度生成一个hash值,并将这个值放到请求头etag中。

3、客户端第二次发起同一个请求时,因为之前请求过此文件,所以本地会有缓存。在请求时会在请求头中加上if-nono-match,其值为服务器返回的etag的值。

4、服务器端比对发送的来的if-none-match的值和本地计算的etag的值是否相同。如果相同,返回304状态码,客户端继续使用本地缓存。如果不相同,返回200状态码,客户端重新解析服务器返回的数据,不使用本地缓存。

具体看下面例子。

二、简单使用

2.1 最简单的使用

最简单的使用就是在configure中加入下面一句话,然后将静态文件放到webroot的路径下,我没有修改webroot指定的路径,所以就是wwwroot文件夹。

 public void configure(iapplicationbuilder app, ihostingenvironment env)
  {
   app.usestaticfiles();
   app.usemvc();
  }

在wwwroot文件夹下放一个名称为1.txt的测试文本,然后通过地址访问。

这种有一个缺点,暴露这个文件的路径在wwwroot下。

2.2 指定请求地址

public void configure(iapplicationbuilder app, ihostingenvironment env)
  {
   app.usemvc();

   app.usestaticfiles(new staticfileoptions()
   {
    fileprovider = new physicalfileprovider(@"c:\users\administrator\desktop"),
    requestpath = new pathstring("/static")
   });

   //app.usestaticfiles("/static");
  }

这种指定了静态文件存放的路径为:c:\users\administrator\desktop,不是使用默认的wwwroot路径,就隐藏了文件的真实路径,并且需要在地址中加上static才能访问。

当然也可以不指明静态文件的路径,只写请求路径,如上面代码中的注释的例子。这样静态文件就必须存储到webroot对应的目录下了。如果webroot的目录对应的是wwwroot,静态文件就放到wwwroot文件夹中。

下面通过例子看一下静态文件的缓存,如果你想做这个例子,别忘记先清空缓存。

(第一次请求)

(第二次请求 文件相对第一次请求没有修改的情况)

(第三次请求 文件相对第一次请求有修改的情况)

三、源码分析

源码在https://github.com/aspnet/staticfiles,这个项目还包含有其他中间件。既然是中间件最重要的就是参数为httpcontext的invoke方法了,因为每一个请求都要经过其处理,然后再交给下一个中间件处理。

下面为处理流程。

public async task invoke(httpcontext context)
  {
   var filecontext = new staticfilecontext(context, _options, _matchurl, _logger, _fileprovider, _contenttypeprovider);

   if (!filecontext.validatemethod())//静态文件的请求方式只能是get或者head
   {
    _logger.logrequestmethodnotsupported(context.request.method);
   }       //判断请求的路径和配置的请求路径是否匹配。如请求路径为http://localhost:5000/static/1.txt        //配置为requestpath = new pathstring("/static")      //则匹配,并将文件路径赋值给staticfilecontext中点的_subpath
   else if (!filecontext.validatepath())
   {
    _logger.logpathmismatch(filecontext.subpath);
   }       //通过获取要访问文件的扩展名,获取此文件对应的mime类型,       //如果找到文件对应的mime,返回true,并将mime类型赋值给staticfilecontext中的_contexttype       //没有找到返回false.
   else if (!filecontext.lookupcontenttype())
   {
    _logger.logfiletypenotsupported(filecontext.subpath);
   }       //判断访问的文件是否存在。       //如果存在返回true,并根据文件的最后修改时间和文件的长度,生成hash值,并将值赋值给_etag,也就是相应头中的etag。       //如果不存在 返回false,进入下一个中间件中处理
   else if (!filecontext.lookupfileinfo())
   {
    _logger.logfilenotfound(filecontext.subpath);
   }
   else
   {
    filecontext.comprehendrequestheaders();          //根据staticfilecontext中的值,加上对应的相应头,并发送响应。具体调用方法在下面
    switch (filecontext.getpreconditionstate())
    {
     case staticfilecontext.preconditionstate.unspecified:
     case staticfilecontext.preconditionstate.shouldprocess:
      if (filecontext.isheadmethod)
      {
       await filecontext.sendstatusasync(constants.status200ok);
       return;
      }
      try
      {
       if (filecontext.israngerequest)
       {
        await filecontext.sendrangeasync();
        return;
       }
       await filecontext.sendasync();
       _logger.logfileserved(filecontext.subpath, filecontext.physicalpath);
       return;
      }
      catch (filenotfoundexception)
      {
       context.response.clear();
      }
      break;
     case staticfilecontext.preconditionstate.notmodified:
      _logger.logpathnotmodified(filecontext.subpath);
      await filecontext.sendstatusasync(constants.status304notmodified);
      return;
     case staticfilecontext.preconditionstate.preconditionfailed:
      _logger.logpreconditionfailed(filecontext.subpath);
      await filecontext.sendstatusasync(constants.status412preconditionfailed);
      return;
     default:
      var exception = new notimplementedexception(filecontext.getpreconditionstate().tostring());
      debug.fail(exception.tostring());
      throw exception;
    }
   }       //进入下一个中间件中处理
   await _next(context);
  }

添加响应头的方法:

public void applyresponseheaders(int statuscode)
  {
   _response.statuscode = statuscode;
   if (statuscode < 400)
   {
    if (!string.isnullorempty(_contenttype))
    {
     _response.contenttype = _contenttype;
    }          //设置响应头中最后修改时间、etag和accept-ranges
    _responseheaders.lastmodified = _lastmodified;
    _responseheaders.etag = _etag;
    _responseheaders.headers[headernames.acceptranges] = "bytes";
   }
   if (statuscode == constants.status200ok)
   {
    _response.contentlength = _length;
   }
   _options.onprepareresponse(new staticfileresponsecontext()
   {
    context = _context,
    file = _fileinfo,
   });
  }

校验文件是否修改的方法:

public bool lookupfileinfo()
  {
   _fileinfo = _fileprovider.getfileinfo(_subpath.value);
   if (_fileinfo.exists)
   {
    _length = _fileinfo.length;
    datetimeoffset last = _fileinfo.lastmodified;
    _lastmodified = new datetimeoffset(last.year, last.month, last.day, last.hour, last.minute, last.second, last.offset).touniversaltime();
          //通过修改时间和文件长度,得到etag的值
    long etaghash = _lastmodified.tofiletime() ^ _length;
    _etag = new entitytagheadervalue('\"' + convert.tostring(etaghash, 16) + '\"');
   }
   return _fileinfo.exists;
  }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对www.887551.com的支持。