asp.netcachinghttp-headerswebserverserver.transfer

Why does HTTP headers doesn't get created when I use Server.Transfer()?


I'm using an .aspx page to serve an image file from the file system according to the given parameters.

Server.Transfer(imageFilePath);

When this code runs, the image is served, but no Last-Modified HTTP Header is created. as opposed to that same file, being called directly from the URL on the same Server.

Therefor the browser doesn't issue an If-Modified-Since and doesn't cache the response.

Is there a way to make the server create the HTTP Headers like normally does with a direct request of a file (image in that case) or do I have to manually create the headers?


Solution

  • I'll expand on @Guffa's answer and share my chosen solution.

    When calling the Server.Transfer method, the .NET engine treats it like an .aspx page, so It doesn't add the appropriate HTTP Headers needed (e.g. for caching) when serving a static file.

    There are three options

    I choose the third option, here is my code:

            try
            {
                DateTime fileLastModified = File.GetLastWriteTimeUtc(MapPath(fileVirtualPath));
                fileLastModified = new DateTime(fileLastModified.Year, fileLastModified.Month, fileLastModified.Day, fileLastModified.Hour, fileLastModified.Minute, fileLastModified.Second);
                if (Request.Headers["If-Modified-Since"] != null)
                {
                    DateTime modifiedSince = DateTime.Parse(Request.Headers["If-Modified-Since"]);
    
                    if (modifiedSince.ToUniversalTime() >= fileLastModified)
                    {
                        Response.StatusCode = 304;
                        Response.StatusDescription = "Not Modified";
                        return;
                    }
                }
                Response.AddHeader("Last-Modified", fileLastModified.ToString("R"));
            }
            catch
            {
                Response.StatusCode = 404;
                Response.StatusDescription = "Not found";
                return;
            }
            Server.Transfer(fileVirtualPath);