Why isn't my custom delivered image caching in the browser?

怎甘沉沦 提交于 2019-12-04 15:37:14

OK, I fixed it.

Here is what I did for anyone else and for my own future reference:

// Check for repeated request for the same image from a browser
if (HttpContext.Current.Request.Headers.Get("If-None-Match") == imgRepGetCache.DateCached.Value.ToString())
{
    // Return 304 - Not Modified
    HttpContext.Current.Response.Status = "304 Not Modified";
}
else
{
    if (imgRepGetCache.DateCached.HasValue)
        HttpContext.Current.Response.Headers.Set("Etag", imgRepGetCache.DateCached.Value.ToString());
    // ... do my other stuff here
}

Works a charm!

If anyone spots any potential problems here, let me know so I can update this.

To pre-empt one obvious one - I can 100% rely on the date string for identifying whether an image is new or not (in my particular scenario).

You don't mention anything in your post about it, but is this a https:// address? Browsers don't cache images and pages from https sites due to security reasons.

The things you need to worry about in the generation of the response are:

  • ETag
  • Expires

The things that you need to worry about when receiving a request are:

  • Last-Modified
  • If-Match
  • If-None-Match
  • If-Modified-Since
  • If-Unmodified-Since
  • Unless-Modified-Since

You might also need to worry about the following http methods:

  • GET
  • HEAD

Here is a solution that should be rather easy to refactor to suite your needs: http://code.google.com/p/talifun-web/wiki/StaticFileHandler

It reads files from the file system and them places them into a cache in memory, so just change it to read from database. Should be an easy job.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!