注册 | 登录 忘记密码? 51cto首页 | 博客 | 论坛 | 招聘
热点文章 用了十年的QQ号,第二次被..
 帮助

ASP.NET中的图片缓存


2008-01-15 15:50:42
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://ssbird.blog.51cto.com/277690/59297

原文地址:
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来测试图片缓存功能,大家可以自由下载.




    文章评论
 
2008-01-23 10:57:31
不错不错 收益匪浅

2008-01-30 16:41:07
好文,顶!

2008-04-17 11:38:31
ConfigurationSection类在哪里?

2008-04-17 21:39:48
ConfigurationSection是.NET自带的类库,完整的路径为:System.Configuration.ConfigurationSection

2008-05-17 17:42:27
不能下载阿CachingHandler.zip 搂主。。。

2008-05-22 14:24:00
该链接继续有效,文件可正常下载,应该是你自己网络的问题,如果还是不能下载请留下你的邮箱,我会发送给你的。

2008-05-27 20:37:42
请搂主发一份到我邮箱
xugang_2008@yahoo.com.cn   谢谢

2008-06-08 22:44:58
楼主 ,有时间发一份到邮箱,谢谢
xugang_2008@yahoo.com.cn   谢谢

现有的下载链接是无效的

2008-06-18 11:12:11
有登陆才可以下载的,嘿嘿

2008-06-24 18:40:35
xg,已发送到你邮箱

 

发表评论

昵   称:
验证码:  点击图片可刷新验证码  博客过2级,无需填写验证码
内   容: