开发者

In an HTTP Handler, is it acceptable to return 304 when you know the content won't change?

I have an HTTP Handler set up which accepts a GUID parameter and returns the image from the file system.

This image will not ever change; the backend program will generate a new GUID if it does. As such, I want the image to always be cached.

开发者_开发问答Is the correct way to do this to set a status code of 304 (not modified) from the HTTP Handler?


I would recommend you setting proper HTTP response headers in order to indicate to the clients that the contents will not change and could be cached:

public void ProcessRequest(HttpContext context)
{
    var cache = context.Response.Cache;
    cache.SetCacheability(HttpCacheability.Public);
    cache.SetExpires(DateTime.Now.Add(CACHE_DURATION));
    cache.SetMaxAge(CACHE_DURATION);
    cache.AppendCacheExtension("must-revalidate, proxy-revalidate");

    byte[] buffer = ...
    context.Response.ContentType = "image/png";
    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}


Yes. However, you should return a HTTP/304 only if the request is conditional request. If you know the image with that URL never changes, you can set a very long expiry date (1 year is the max according to the specs).

BTW, RFC 2616 is quite easy to read -- I suggest to take look there, for further details.


Also in addition to @Darin's response, have you come across ETags? These are one of the common way of implementing caching like you propose. The first time the browser requests the image you won't have an ETag so you know to serve up the image. The next time a request is made it will provide the ETag - which you can then use to see whether to return a 304 or the image itself. In your example you would only be checking for the presence of an ETag or not.

With your proposed solution what would concern me is how do you identify the first request from subsequent requests (and from more than one client)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜