设置远期未来会在代码中过期 - ASP.NET

Sun*_*oot 6 c# asp.net iis optimization web-optimization

有没有办法可以用ASP.NET以编程方式在代码中设置Expires Header?具体来说,我需要将它设置在整个文件夹和所有子文件夹上,并且该文件夹仅包含静态文件(JavaScript,CSS,图像等)而不包含aspx文件,因此我不能只将一些代码添加到aspx代码中-behind page_load.

我通常可以直接在IIS中设置它.但服务器被客户端锁定(我只有FTP访问Web应用程序目录进行部署),并且让客户端在IIS上设置Expires Header将需要一个冰河时代(它是一个公共部门/政府网站).

我按照雅虎的建议http://developer.yahoo.com/performance/rules.html#expires进行前端优化的原因

更新:我试过创建一个HttpModule ......

public class FarFutureExpiresModule : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;

        string url = context.Request.Url.ToString();

        if (url.Contains("/StaticContent/"))
        {
            context.Response.Cache.SetExpires(DateTime.Now.AddYears(30));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然这看起来不起作用.我在代码上放置了一个断点,它可以正常运行.但是,当我在Firefox中分析原始HTTP标头信息时,未设置过期值.请注意我正在使用BeginRequest,但我也尝试连接到PostReleaseRequestState和PreSendRequestHeaders,它们似乎也不起作用.有任何想法吗?

更新2:好的,所以看起来因为我正在运行IIS6,HttpModules不会运行静态文件,只运行动态文件(*.aspx等).感谢RickNZ的帮助,我提出了以下IHttpModule:

public class FarFutureExpiresModule : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;

        string url = context.Request.Url.ToString();

        if (url.Contains("/StaticContent/"))
        {
            context.Response.Cache.SetExpires(DateTime.Now.AddYears(30));
            context.Response.Cache.SetMaxAge(TimeSpan.FromDays(365.0 * 3.0));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

...它似乎有效,但只能在Visual Studio中的内置Web服务器和IIS7中(在Intergrated Pipeline模式下).一位工作同事提到在IIS6上设置通配符映射以使HttpModules处理静态文件,但是如果我可以访问IIS6,我可以直接设置Far-Future Expires标头而不用打扰这个HttpModule.那好吧!

Ric*_*kNZ 3

如果您使用的是 IIS 7,最简单的方法是编写一个在集成模式下为静态文件运行的 HttpModule,并从那里设置 Expires 和 Cache-Control 标头。

更新:

你的 HttpModule 应该可以工作,尽管我通常也会调用:

context.Response.Cache.SetMaxAge(TimeSpan.FromDays(365.));
Run Code Online (Sandbox Code Playgroud)

更新2:

使用 IIS 6,您必须以编程方式修改元数据库。这是可能的,尽管它需要提升的权限。

唯一的其他选择是用 C++ 编写 ISAPI 模块。