c# - 使用 ASP.Net,如何为静态内容启用浏览器缓存并为动态内容禁用它?

标签 c# asp.net asp.net-4.0

我发现了很多关于让浏览器避免缓存动态内容(例如 .aspx 页面)的好信息,但是我没有成功让浏览器缓存我的静态内容,特别是 css、javascript 和图像文件。

我一直在 Global.asax 中使用 Application_BeginRequest 但没有成功。对于我们来说,拥有一个单独的静态内容服务器不是一个选择。我还希望避免配置 IIS 设置,除非可以从 web.config 控制它们。禁用 aspx 页面的缓存会影响其上显示的静态内容的缓存吗?

如果这个问题之前已被回答过,我深表歉意。

作为讨论的起点,这里是我的 Global.asax 文件的隐藏代码。

public class Global_asax : System.Web.HttpApplication
{
    private static HashSet<string> _fileExtensionsToCache;

    private static HashSet<string> FileExtensionsToCache
    {
        get 
        {
            if (_fileExtensionsToCache == null) 
            {
                _fileExtensionsToCache = new HashSet<string>();

                _fileExtensionsToCache.Add(".css");
                _fileExtensionsToCache.Add(".js");
                _fileExtensionsToCache.Add(".gif");
                _fileExtensionsToCache.Add(".jpg");
                _fileExtensionsToCache.Add(".png");
            }

            return _fileExtensionsToCache;
        }
    }

    public void Application_BeginRequest(object sender, EventArgs e)
    {
        var cache = HttpContext.Current.Response.Cache;

        if (FileExtensionsToCache.Contains(Request.CurrentExecutionFilePathExtension)) 
        {
            cache.SetExpires(DateTime.UtcNow.AddDays(1));
            cache.SetValidUntilExpires(true);
            cache.SetCacheability(HttpCacheability.Private);
        } 
        else 
        {
            cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            cache.SetValidUntilExpires(false);
            cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetNoStore();
        }
    }
}

最佳答案

如果您使用的是 IIS7,并且想要缓存静态内容,请按照 documentation 在 web.config 中添加以下内容: :

<configuration>
  <system.webServer>
    <staticContent>
      <clientCache httpExpires="Sun, 27 Sep 2015 00:00:00 GMT" cacheControlMode="UseExpires" />
    </staticContent>
  </system.webServer>
</configuration>

关于c# - 使用 ASP.Net,如何为静态内容启用浏览器缓存并为动态内容禁用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7526381/

相关文章:

c# - 在 XNA 中获取轻拂手势的起始位置

asp.net - 使用 .Resx 文件作为全局应用程序消息?

asp.net - 使用 ASP.NET 4.0 和 IIS7 进行 HTTP 压缩

asp.net - 如何以声明方式创建带有数据绑定(bind)参数的 RouteUrls?

python - 如何使用 Viewstate 参数抓取页面请求?

c# - 遍历一个类的属性

c# - 网格中的StackPanel : limit height

c# - 通过对大文本多次调用 Regex.IsMatch 来优化性能

C# public 仅适用于相同接口(interface)的类

asp.net - 使用 web.config 禁止用户代理