asp.net – 如何为客户端和服务器缓存设置不同的缓存到期时间

我想让某些页面有10分钟的缓存用于客户端和24小时的服务器.原因是如果页面更改,客户端将在10分钟内获取更新的版本,但如果没有更改,服务器将只需要一天重新生成页面一次.

问题是输出缓存设置似乎覆盖客户端设置.这是我设置的:

自定义ActionFilterattribute类

public class ClientCacheAttribute : ActionFilterattribute
{
    private bool _noClientCache;

    public int ExpireMinutes { get; set; }

    public ClientCacheAttribute(bool noClientCache) 
    {
        _noClientCache = noClientCache;
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        if (_noClientCache || ExpireMinutes <= 0)
        {
            filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            filterContext.HttpContext.Response.Cache.SetNoStore();
        }
        else
        {
            filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(ExpireMinutes));
        }

        base.OnResultExecuting(filterContext);
    }
}

Web配置设置

<outputCacheSettings>
    <outputCacheProfiles>
      <add name="Cache24Hours" location="Server" duration="86400" varyByParam="none" />
    </outputCacheProfiles>
  </outputCacheSettings>

我叫什么

[OutputCache(CacheProfile = "Cache24Hours")]
[ClientCacheAttribute(false,ExpireMinutes = 10)]
public class HomeController : Controller
{
  [...]
}

但是看HTTP头部显示

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1

如何正确实施?它是一个ASP.NET MVC 4应用程序.

解决方法

您需要实现自己的服务器端缓存解决方案,客户端缓存使用ClientCacheAttribute或OutputCache.以下是为什么您需要服务器端缓存的自定义解决方案的原因.

> ClientCacheAttribute将缓存策略设置为Response.Cache,它是HttpCachePolicyBase的类型
>和内置的OutputCache也将缓存策略设置为Response.Cache

这里我要强调的是,我们没有HttpCachePolicyBase的集合,但是我们只有一个HttpCachePolicyBase对象,所以我们不能为给定的响应设置多个缓存策略.

即使我们可以将Http Cacheability设置为HttpCacheability.ServerAndPrivate,但是再次,您将在其他问题中运行缓存持续时间(即,客户端10分钟和24小时服务器)

我建议的是使用OutputCache进行客户端缓存,并实现自己的缓存服务器端缓存机制.

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...