[ASP.NET]ASP.NET中的图片缓存

原文地址:Caching Images in ASP.NET , 版权归原文作者所有。
引言:
在一个Web应用程序中,可以通过很多种方法来改善其性能,其中最简单但也是最有效的方法就是在客户端缓存图片,这篇文章就是告诉你如何在你的站点中实现图片的缓存。

问题:
我曾经建立过一个站点,在CSS样式表中使用了很多图片来作为菜单项的背景。网站完成之后,我使用Microsoft Network Monitor微软的一款流量分析工具,可从微软下载中心下载网站的流量进行了统计,发现每次对首页的访问都会对20个不同的文件发出请求,其中一半以上都来至于对菜单背景图片的请求。
 
有两种方法可以解决这个问题,第一种方法是通过IIS实现图片的缓存;第二种方法是直接在ASP.NET实现缓存。
通过IIS缓存图片:
这种方法非常简单,首先选中IIS管理器中选中一个文件或文件夹,右键单击,打开属性对话框。

选中HTTP头选项卡中的“启用内容过期”,并根据需要设定过期时间。这样客户端就会对你设定的文件进行缓存,直到缓存过期才会向服务端发起新的请求。
当你对IIS拥有足够的管理权限,并且网站的图片位置相对比较集中时,这种方法是一种很好的选择。但这样的条件往往得不到满足,这个时候你就需要使用第二种方法了。
通过HttpHandle缓存图片
为了获取对ASP.NET的请求,需要编写一个自定义HttpHandle来对图片文件(*.jpg;*.gif;*.png)进行监听。首先在Visuan Studio中新建一个类库工程,取名为
CachingHandler,负责处理对图片的请求。CachingHandler需要实现IHttpHandle接口,在IHttpHandle接口中,IsReusable属性指示其他请求是否可以使用该IHttpHandler实例ProcessRequest()方法负责获取和发送数据。

namespace SoftwareArchitects.Web
{
  public class CachingHandler : IHttpHandler
  {
    public bool IsReusable
    {
      get { return true; }
    }
  
    public void ProcessRequest(HttpContext context)
    {
      string file = context.Server.MapPath
        (context.Request.FilePath.Replace(".ashx", ""));
      string filename = file.Substring(file.LastIndexOf('\\') + 1);
      string extension = file.Substring(file.LastIndexOf('.') + 1);
      CachingSection config = (CachingSection)context.GetSection
        ("SoftwareArchitects/Caching");
      if (config != null)
      {
        context.Response.Cache.SetExpires
          (DateTime.Now.Add(config.CachingTimeSpan));
        context.Response.Cache.SetCacheability
            (HttpCacheability.Public);
        context.Response.Cache.SetValidUntilExpires(false);

          FileExtension fileExtension = config.FileExtensions[extension];
        if (fileExtension != null)
       {
          context.Response.ContentType = fileExtension.ContentType;
       }
     }
    context.Response.AddHeader("content-disposition",
    "inline; filename=" + filename);
    context.Response.WriteFile(file);
    }
  }
}

   
配置Web.Config文件
    在上面的代码中,我们使用了一个自定义类ConfigurationSection来读写Web.Config的信息,下面是这个类的实现。

namespace SoftwareArchitects.Web.Configuration
{
  /// <summary>
  /// Configuration for caching
  /// </summary>
  public class CachingSection : ConfigurationSection
  {
    [ConfigurationProperty("CachingTimeSpan", IsRequired = true)]
    public TimeSpan CachingTimeSpan
    {
      get { return (TimeSpan)base["CachingTimeSpan"]; }
      set { base["CachingTimeSpan"] = value; }
    }

    [ConfigurationProperty("FileExtensions", IsDefaultCollection = true,
      IsRequired = true)]
    public FileExtensionCollection FileExtensions
    {
      get { return ((FileExtensionCollection)base["FileExtensions"]); }
    }
  }
/// <summary>
  /// List of available file extensions
  /// </summary>
  public class FileExtensionCollection : ConfigurationElementCollection
  {
    …
  }
/// <summary>
  /// Configuration for a file extension
  /// </summary>
  public class FileExtension : ConfigurationElement
  {
    [ConfigurationProperty("Extension", IsRequired = true)]
    public string Extension
    {
      get { return (string)base["Extension"]; }
      set { base["Extension"] = value.Replace(".", ""); }
    }
  
    [ConfigurationProperty("ContentType", IsRequired = true)]
    public string ContentType
    {
      get { return (string)base["ContentType"]; }
      set { base["ContentType"] = value; }
    }
  }
}

    完整的ConfigurationSection类:CachingSection.cs
    最后是在Web.Config文件中添加相关的信息:
   

<configuration>
  <configSections>
    <sectionGroup name="SoftwareArchitects">
      <section name="Caching" requirePermission="false"
        type="SoftwareArchitects.Web.Configuration.CachingSection,
        SoftwareArchitects.Web.CachingHandler" />
    </sectionGroup>
  </configSections>
  <SoftwareArchitects>
    <Caching CachingTimeSpan="1">
      <FileExtensions>
        <add Extension="gif" ContentType="image\gif" />
        <add Extension="jpg" ContentType="image\jpeg" />
        <add Extension="png" ContentType="image\png" />
      </FileExtensions>
    </Caching>
  </SoftwareArchitects>
  …
<httpHandlers>
    <add verb="*" path="*.gif.ashx"
      type="SoftwareArchitects.Web.CachingHandler,
      SoftwareArchitects.Web.CachingHandler"/>
    <add verb="*" path="*.jpg.ashx"
      type="SoftwareArchitects.Web.CachingHandler,
      SoftwareArchitects.Web.CachingHandler"/>
    <add verb="*" path="*.png.ashx"
      type="SoftwareArchitects.Web.CachingHandler,
      SoftwareArchitects.Web.CachingHandler"/>
  </httpHandlers>
</configuration>

    在站点中完成以上代码的添加之后,再次使用Microsoft Network Monitor进行测试,第一次访问首页时依然是20个不同的请求,但到了第二次访问请求就变为了7个,因为所有的图片文件都已经缓存到了客户端。

    在原文中,作者还提供了一个完整的Solution来测试图片缓存功能,大家可以自由下载.

赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏