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

孤者浪人 提交于 2019-12-04 12:04:47

When you make a transfer to the file, the server will return the same headers as it does for an .aspx file, because it's basically executed by the .NET engine.

You basically have two options:

  • Make a redirect to the file instead, so that the browser makes the request for it.

  • Set the headers you want, and use Request.BinaryWrite (or smiiliar) to send the file data back in the response.

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

  • Using Response.Redirect, so the browser makes the appropriate request
  • Setting the headers needed and using Request.BinaryWrite to serve the content
  • Setting the headers needed and calling Server.Transfer

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!