加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 22:46:29 所属栏目:asp.Net 来源:网络整理
导读:我想让某些页面有10分钟的缓存用于客户端和24小时的服务器.原因是如果页面更改,客户端将在10分钟内获取更新的版本,但如果没有更改,服务器将只需要一天重新生成页面一次. 问题是输出缓存设置似乎覆盖客户端设置.这是我设置的: 自定义ActionFilterAttribute类
我想让某些页面有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进行客户端缓存,并实现自己的缓存服务器端缓存机制.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读