Is it possible to always return http 304 status for requests with "If-Modified-Since" if the content is static

In our Asp.Net application, we have IHttpHandler processing requests for images. The handler is called with a special identifier that identifies the image in our image cache. When an image is placed in cash, it never changes. My question is:

Is it possible to always return an http 304 status code for requests with the heading "If-Modified-Since" without actually checking this date? The reason is that the browser should already have a copy of the image (since it provided a title with a changed name).

This will simplify life, because we do not yet track the date the image was created.

Here is the actual code (Update: I have included the if-modified header now in the server response, as recommended by Aristos):

public void ProcessRequest(HttpContext context)
{
    if (!String.IsNullOrEmpty(context.Request.Headers["If-Modified-Since"])) {
        //Is this okay?
        context.Response.StatusCode = 304;
        context.Response.StatusDescription = "Not Modified";
        return;
    }
    var thumbnailId = context.Request.QueryString["thumbnail"];
    using (var thumbnailCache = new CThumbnailCache()) {
        var imageBytes = thumbnailCache.GetImageById(thumbnailId);

        context.Response.ContentType = "image/png";
        var outputStream = context.Response.OutputStream;
        outputStream.Write(imageBytes, 0, imageBytes.Count());
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.Cache.SetLastModified(DateTime.UtcNow);
        // added after Aristos post
        context.Response.AddHeader("If-Modified-Since", DateTime.UtcNow.ToString("r"));

        const int maxAge = 86400 * 14; // 14 Tage
        context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(maxAge));
        context.Response.Cache.SetMaxAge(new TimeSpan(0, 0, maxAge));
        context.Response.CacheControl = "private";
        context.Response.Cache.SetValidUntilExpires(true);

    }
}
+5
source share
2 answers

its good, from the moment you get the If-Modified-Sinceresource in the browser, and you decide whether you allow it as it is.

I like to say what you think here. It seems to you that you are not setting this header, so you probably will not get it in the browser.

To do this actual work you need to add this line

context.Response.AddHeader("If-Modified-Since", LastModifledOfImage.ToString()); 

or how you send the current date-time:

context.Response.AddHeader("If-Modified-Since", DateTime.UtcNow.ToString());

when sending the image. I see what you are usingSetLastModified , but that means the title is Last-Modifiednot the one you are checking.

, , , If-Modified-Since , .

+3

:

GET , , .

, , . Date .

+2

All Articles