将过期标头添加到Web.Config文件

时间:2011-11-11 11:10:26

标签: iis web-config

我希望将expire标头添加到我的网站,以便为文件设置缓存时间。

我已经找到了以下示例,但我想将其设置为仅在可能的情况下缓存JPG,PNG,GIF,JS和CSS文件?

<system.webServer>
    <staticContent>
        <clientCache cacheControlMaxAge="14.00:00:00" cacheControlMode="UseMaxAge"/>
    </staticContent>
</system.webServer>

感谢您的帮助!

4 个答案:

答案 0 :(得分:4)

您可以做的是在文件所在的文件夹中创建web.config文件。 (您可能有图像文件夹“图像”用于图像,“Js”用于javascript文件,“Css”用于样式表...等等)然后,将yor代码粘贴到这些文件中。通过这样做,您可以将缓存settigs应用于这些文件夹中的所有文件,而不管文件类型如何。这比将缓存设置应用于特定文件扩展名更灵活。

答案 1 :(得分:3)

IIS不支持静态内容的动态过期标头。

您可以通过以下方式添加静态过期标头:

<system.webServer>
  <staticContent>
      <clientCache httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" cacheControlMode="UseExpires" />
  </staticContent>
</system.webServer>

来源: The Official Microsoft IIS site

这里有一个类似的问题: IIS 7.5 How do you add a Dynamic HTTP Expires Header

答案 2 :(得分:1)

正如已经指出的那样,使用特定文件夹中的另一个web.config可能是最佳选择。

但是,您可以使用和出站重写规则覆盖缓存控制标头:

<system.webServer>
...
<rewrite>
  <outboundRules>
    <rule name="RewriteCacheControlForHTMLFiles" preCondition="jsFile">
        <match serverVariable="RESPONSE_Cache_Control" pattern=".*" />
        <action type="Rewrite" value="max-age=86400" />
    </rule>
    <preConditions>
        <preCondition name="jsFile">
            <add input="{REQUEST_FILENAME}" pattern="\.js$" />
        </preCondition>
    </preConditions>
  </outboundRules>
  ...

答案 3 :(得分:0)

如果你想缓存特定的项目,我会以编程方式执行此操作。您可以使用以下代码来帮助您前进。它来自微软,我把它带过去,所以你不必去寻找它。 http://msdn.microsoft.com/en-us/library/ff477235.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Caching;
using System.IO;

public partial class _Default : System.Web.UI.Page
{


    protected void Button1_Click1(object sender, EventArgs e)
    {
        ObjectCache cache = MemoryCache.Default;
        string fileContents = cache["filecontents"] as string;

        if (fileContents == null)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration =
                DateTimeOffset.Now.AddSeconds(10.0);

            List<string> filePaths = new List<string>();
            string cachedFilePath = Server.MapPath("~") +
                "\\cacheText.txt";

            filePaths.Add(cachedFilePath);

            policy.ChangeMonitors.Add(new
                HostFileChangeMonitor(filePaths));

            // Fetch the file contents.
            fileContents = File.ReadAllText(cachedFilePath) + "\n"
                + DateTime.Now.ToString();

            cache.Set("filecontents", fileContents, policy);

        }

        Label1.Text = fileContents;
    }
}
相关问题