2012-12-20 73 views
3

我正在使用ImageResizing库来调整大小并在我的C#Mvc应用程序中传递图像。在MVC应用程序中缓存图像的正确方法

有一件事情没有发生,虽然我的图片没有被缓存。

我很努力去理解为每幅图像适当地添加缓存需要什么。

我只需要知道我是否在写轨道?这会缓存我的图片吗?

我想我需要做的,是集FinalContentType,并FinalContentType在我ImageResizer_OnPostAuthorizeRequestStart(我不知道从哪里得到这些值)

然后,我希望在Application_PreSendRequestHeaders我可以使用以下代码正确设置缓存标头。

我已经使用了here所述方法的修改版本。

这里是我的代码:

private static void ImageResizer_OnPostAuthorizeRequestStart(IHttpModule sender2, HttpContext context) 
     { 
      string path = Config.Current.Pipeline.PreRewritePath; 
      if (!path.StartsWith(PathUtils.ResolveAppRelative("~/s3"), StringComparison.OrdinalIgnoreCase)) return; 
     Config.Current.Pipeline.SkipFileTypeCheck = true; 
     Config.Current.Pipeline.ModifiedQueryString["cache"] = ServerCacheMode.Always.ToString(); 
    } 

    protected void Application_PreSendRequestHeaders(Object source, EventArgs e) 
    { 
     var app = source as HttpApplication; 

     HttpContext context = (app != null) ? app.Context : null; 

     if (context != null && context.Items != null && context.Items["FinalContentType"] != null && context.Items["LastModifiedDate"] != null) 
     { 
      //Clear previous output 
      //context.Response.Clear(); 
      context.Response.ContentType = context.Items["FinalContentType"].ToString(); 

      //FinalContentType is set to image/jpeg or whatever the image mime-type is earlier in code. 
      //Add caching headers 
      int mins = 1; //Or Configuration.AppSettings['whatever'] 

      if (mins > 0) 
      { 
       context.Response.Expires = 1; 
      } 

      var lastModified = (DateTime?)context.Items["LastModifiedDate"]; //Set earlier in code. 

      if (lastModified != DateTime.MinValue) 
      { 
       Response.Cache.SetLastModified(lastModified.Value); 
      } 

      Response.Cache.SetCacheability(context.Request.IsAuthenticated ? HttpCacheability.Private : HttpCacheability.Public); 
     } 

    } 
+0

'OutputCacheAttribute'没有做你想做的事吗?链接:http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v=vs.108).aspx –

+0

这些图像在运行时由库重新调整,以便缓存属性不起作用,也是我特别想要缓存的图像。 – shenku

+1

为什么它不工作? MSDN表示它将缓存内存中的操作方法的输出。从本质上讲,我明白,无论写到响应中的任何内容都被保存在内存中,那就是你的二进制图像数据。 –

回答

4

使用DiskCache和ClientCache插件来分别处理磁盘高速缓存和缓存头。

ASP.NET输出缓存在这里没用。

+1

为什么输出缓存在这里没用?你能详细说明吗? – DarthVader

+0

我不确定它是无用的。 http://www.codeguru.com/csharp/.net/net_asp/article.php/c19835/Creating-a-Custom-Output-Cache-Provider-in-ASPNET-4.htm的快速扫描看起来很有前途(尽管再次,不使用ImageResizing)。我记得ImageResizing的DiskCache插件的好处是,IIRC有很多技巧用于限制执行的.NET代码的数量,IIS“直接处理文件”。 http://imageresizing.net/plugins/diskcache – JayC

+0

尝试clientcache我认为这是要走的路,但不是那里,其他建议欢迎,而我尝试 – shenku

相关问题