.NET 4.0实现OutputCacheProvider

aza*_*arp 5 asp.net caching .net-4.0

我正在检查ASP.NET 4.0中的OutputCacheProvider并使用它将我的输出缓存存储到MongoDb数据库中.我无法理解Add方法的目的,它是OutputCacheProvider的覆盖方法之一.将VaryByParam设置为某个值时,将调用Add方法.所以,如果我有VaryByParam ="id",那么将调用Add方法.

但是在调用Add the Set之后我也可以在Set方法中插入MongoDb数据库.

public override void Set(string key, object entry, DateTime utcExpiry)
{
    // if there is something in the query use the path and query to generate the key 
    var url = HttpContext.Current.Request.Url;

    if (!String.IsNullOrEmpty(url.Query))
    {
        key = url.PathAndQuery;
    }

    Debug.WriteLine("Set(" + key + "," + entry + "," + utcExpiry + ")");  
    _service.Set(
        new CacheItem() { Key = MD5(key), Item = entry, Expires = utcExpiry }
    ); 
}
Run Code Online (Sandbox Code Playgroud)

在Set方法中,我使用PathAndQuery获取QueryString的参数,然后在密钥上执行MD5并将其保存到MongoDb数据库中.

如果我正在做类似VaryByParam ="custom"之类的东西,似乎Add方法会很有用.

任何人都可以对OutputCacheProvider的Add方法有所了解吗?

Dav*_*ner 8

他们是相似的,但有一点点差异.查看OutputCacheProvider类的MSDN文档

  • Set - "将指定的条目插入到输出缓存中,如果条目已被缓存,则覆盖该条目"
  • 添加 - "将指定的条目插入输出缓存".

"添加"的评论继续说

"如果指定键的缓存中已有值,则提供程序必须返回该值.提供程序不得存储使用Add方法参数传递的数据.Add方法存储数据(如果数据尚未存在)如果数据在缓存中,Add方法返回它"

因此,对于尚未存在于缓存中的新值,它们的行为相同,但是当值已经存在时,Set会更新它,而Add会保留原始值.