I\'m serving up an image from a database using an IHttpHandler. The relevant code is here:
public void ProcessRequest(HttpContext context)
{
context.Resp
This is how it's done in Roadkill's (a .NET wiki) file handler:
FileInfo info = new FileInfo(fullPath);
TimeSpan expires = TimeSpan.FromDays(28);
context.Response.Cache.SetLastModifiedFromFileDependencies();
context.Response.Cache.SetETagFromFileDependencies();
context.Response.Cache.SetCacheability(HttpCacheability.Public);
int status = 200;
if (context.Request.Headers["If-Modified-Since"] != null)
{
status = 304;
DateTime modifiedSinceDate = DateTime.UtcNow;
if (DateTime.TryParse(context.Request.Headers["If-Modified-Since"], out modifiedSinceDate))
{
modifiedSinceDate = modifiedSinceDate.ToUniversalTime();
DateTime fileDate = info.LastWriteTimeUtc;
DateTime lastWriteTime = new DateTime(fileDate.Year, fileDate.Month, fileDate.Day, fileDate.Hour, fileDate.Minute, fileDate.Second, 0, DateTimeKind.Utc);
if (lastWriteTime != modifiedSinceDate)
status = 200;
}
}
context.Response.StatusCode = status;
Thomas's answer about IIS not supplying the status code is the key, without it you just get 200s back each time.
The browser will simply send you a date and time for when it thinks the file was last modified (no no header at all), so if it differs you just return a 200. You do need to normalize your file's date to remove milliseconds and ensure it's a UTC date.
I've gone for defaulting to 304s if there's a valid modified-since, but that can be tweaked if needed.