2009-08-03 174 views
0

通过使用下面的功能我缓存JS,在浏览器的CSS文件。缓存文件浏览器中的

就像聪明我想cahe在浏览器中的图像。

private static void CacheOrFetchFromServer(string relativePath, string absolutePath, HttpContext context) 
{ 
    Cache cache = HttpRuntime.Cache; 
    string content; 
    if (cache[relativePath] == null) 
    { 
     Encoding encoding = Encoding.GetEncoding(DefaultEncodingCodePage); 
     CacheDependency dependency = new CacheDependency(absolutePath); 

     content = File.ReadAllText(absolutePath, encoding); 
     cache.Insert(relativePath, content, dependency); 
    } 
    else 
    { 
     content = cache[relativePath].ToString(); 
    } 

    using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) 
    { 
     sw.Write(content); 
    } 
} 

我已经尝试了下面的一个缓存图像。但它没有显示图像。

private static void CacheOrFetchImageFileFromServer(string relativePath, string absolutePath, HttpContext context) 
{ 
    string extension = System.IO.Path.GetExtension(relativePath); 
    if (extension.ToUpper() == ".JPG" || extension.ToUpper() == ".PNG" || extension.ToUpper() == ".GIF" || extension.ToUpper() == ".TIFF") 
    { 
     Cache cache = HttpRuntime.Cache; 
     System.Drawing.Image imgPhoto = null; 
     if (cache[relativePath] == null) 
     { 
      Encoding encoding = Encoding.GetEncoding(DefaultEncodingCodePage); 
      CacheDependency dependency = new CacheDependency(absolutePath); 

      FileStream fs = File.OpenRead(absolutePath); 
      byte[] data = new byte[fs.Length]; 
      fs.Read(data, 0, data.Length); 

      MemoryStream ms = new MemoryStream(data); 
      Bitmap bmp = new Bitmap(ms); 

      imgPhoto = System.Drawing.Image.FromFile(absolutePath); 
      cache.Insert(relativePath, bmp, dependency); 
     } 
     else 
     { 
      imgPhoto = (Image) cache[relativePath]; 
     } 

     context.Response.Write(absolutePath); 


     //using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) 
     //{ 
     // sw.Write(absolutePath); 
     //} 
    } 
} 

回答

2

我不知道我明白你在这里做什么。所有的
首先,Cache对象在asp.net用于缓存数据的服务器侧,而不是在客户端(浏览器)。文件
缓存,特别是CSS,JavaScript和图像,是通过自动浏览器中完成,您不必为每个文件手动完成。即使您必须手动执行此操作,这也不是方法 - 看起来您只是在服务器的缓存中创建了一个文件副本(我没有做过测试,但我相信微软并假设这是已经以某种方式完成了,而你的方式实际上更慢)。
如果你想在客户端缓存更大的控制权,您可以启用上的IIS内容过期。