Sam
Sam

Reputation: 4339

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?

Upvotes: 1

Views: 1270

Answers (3)

Paul Hadfield
Paul Hadfield

Reputation: 6136

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)

Upvotes: 0

alienhard
alienhard

Reputation: 14692

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.

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

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);
}

Upvotes: 2

Related Questions