2

I have a created an image controller that retrieves images from a database. They are using non parametrized URL (/Images/ShowCategory/1). My problem comes from that they are not being cache. I have setup my method to set the Cacheability, expire time, and max age. Yet it still does not cache the image. I am also using the OutputCaching attribute on this method [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]. I never get a 304 Not Modified response from the server. Is there something that I am missing here?

Request.RequestContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.Public);
Request.RequestContext.HttpContext.Response.Cache.SetExpires(DateTime.Now.AddDays(7));
Request.RequestContext.HttpContext.Response.Cache.SetMaxAge(new TimeSpan(7, 0, 0, 0));

byte[] image = (from c in db.Categories
                where c.ID == id
                select c.Image).FirstOrDefault();

Image img;
Size size = new Size(225, 175);

using (MemoryStream ms = new MemoryStream())
{
    if (image == null)
    {
        string path = Server.MapPath(@"~\Images\NoImage.png");
        img = Image.FromFile(path);
    }
    else
        img = Image.FromStream(new MemoryStream(image, 0, image.Length));

    img = (Image)new Bitmap(img, size);
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    image = ms.ToArray();
}

return File(image, "image/jpeg");

Response:

HTTP/1.1 200 OK
Cache-Control: private, max-age=604800
Content-Type: image/jpeg
Expires: Thu, 16 Oct 2014 15:09:21 GMT
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Thu, 09 Oct 2014 15:09:21 GMT
Content-Length: 40317
ios85
  • 2,104
  • 7
  • 37
  • 55
  • Have you tried using the [`OutputCacheAttribute`](http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v=vs.118).aspx)? – DavidG Oct 09 '14 at 15:23
  • @DavidG Yes, i forgot to mention that. Thanks for the heads up. – ios85 Oct 09 '14 at 15:28
  • 1
    Does this help? http://stackoverflow.com/questions/23775040/configure-the-mvc-net-outputcache-to-return-304-not-modified-if-an-actionresult – DavidG Oct 09 '14 at 15:30
  • @DavidG yes that did the trick. Thank you not sure why my searching didnt turn that up earlier. – ios85 Oct 09 '14 at 17:13

0 Answers0