为什么HTTP头没有得到当我用Server.Transfer的()产生的? [英] Why does HTTP headers doesn't get created when I use Server.Transfer()?

查看:182
本文介绍了为什么HTTP头没有得到当我用Server.Transfer的()产生的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是.aspx页面中根据给定参数从文件系统服务的图像文件。

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

Server.Transfer(imageFilePath);

在此code运行时,图像送达,但没有的的Last-Modified 的HTTP创建头。
相对于同一文件,从同一个服务器上的URL直接调用。

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.

为此浏览器未发出的如果-Modified-Since的的和不缓存响应。

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

有没有一种方法,使服务器创建的HTTP头像(在这种情况下图像)的文件的直接请求一般不会或做我必须手动创建的头?

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?

推荐答案

我会扩大@ Guffa的答案,并分享我选择的解决方案。

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

在调用 Server.Transfer的方法时,.NET引擎将它像一个的.aspx 页,所以它并不需要添加相应的HTTP头文件(例如缓存)提供一个静态文件时。

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.

有三个选项


  • 使用的Response.Redirect ,所以浏览器进行适当的请求

  • 设置页眉需要使用 Request.BinaryWrite 服务内容

  • 设置所需的头文件并调用 Server.Transfer的

  • 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

我选择第三个选项,这里是我的code:

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

这篇关于为什么HTTP头没有得到当我用Server.Transfer的()产生的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆