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()方法负责获取和发送数据。

InBlock.gif namespace SoftwareArchitects.Web
InBlock.gif{
InBlock.gif   public class CachingHandler : IHttpHandler
InBlock.gif  {
InBlock.gif     public bool IsReusable
InBlock.gif    {
InBlock.gif      get { return true; }
InBlock.gif    }
InBlock.gif  
InBlock.gif     public void ProcessRequest(HttpContext context)
InBlock.gif    {
InBlock.gif       string file = context.Server.MapPath
InBlock.gif        (context.Request.FilePath.Replace( ".ashx", ""));
InBlock.gif      string filename = file.Substring(file.LastIndexOf('\\') + 1);
InBlock.gif      string extension = file.Substring(file.LastIndexOf('.') + 1);
InBlock.gif      CachingSection config = (CachingSection)context.GetSection
InBlock.gif        ( "SoftwareArchitects/Caching");
InBlock.gif      if (config != null)
InBlock.gif      {
InBlock.gif        context.Response.Cache.SetExpires
InBlock.gif          (DateTime.Now.Add(config.CachingTimeSpan));
InBlock.gif        context.Response.Cache.SetCacheability
            (HttpCacheability.Public);
InBlock.gif        context.Response.Cache.SetValidUntilExpires( false);
InBlock.gif
          FileExtension fileExtension = config.FileExtensions[extension];
InBlock.gif        if (fileExtension != null)
InBlock.gif       {
InBlock.gif          context.Response.ContentType = fileExtension.ContentType;
InBlock.gif       }
InBlock.gif     }
InBlock.gif    context.Response.AddHeader( "content-disposition",
InBlock.gif     "inline; filename=" + filename);
InBlock.gif    context.Response.WriteFile(file);
InBlock.gif    }
InBlock.gif  }
InBlock.gif}
   
配置Web.Config文件
    在上面的代码中,我们使用了一个自定义类 ConfigurationSection来读写Web.Config的信息,下面是这个类的实现。

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

    完整的 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来测试图片缓存功能,大家可以自由下载.

转载于:https://www.cnblogs.com/xuelian/archive/2008/08/21/1272661.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值