webapi缓存 System.Runtime.Caching
webapi缓存添加
缓存操作类:
public class MemoryCacheDefault { private static readonly MemoryCache _cache = MemoryCache.Default; public void RemoveStartsWith(string key) { lock (_cache) { _cache.Remove(key); } } public T Get<T>(string key) where T : class { var o = _cache.Get(key) as T; return o; } [Obsolete("Use Get<T> instead")] public object Get(string key) { return _cache.Get(key); } public void Remove(string key) { lock (_cache) { _cache.Remove(key); } } public bool Contains(string key) { return _cache.Contains(key); } public void Add(string key, object o, DateTimeOffset expiration) { var cachePolicy = new CacheItemPolicy { AbsoluteExpiration = expiration }; lock (_cache) { _cache.Set(key, o, cachePolicy); } } public IEnumerable<string> AllKeys { get { return _cache.Select(x => x.Key); } } }
MemoryCacheDefault _cache = new MemoryCacheDefault(); _cache.Add(cacheKey, new AjaxResult(token.access_token), DateTimeOffset.Now.AddSeconds(6000)); if (_cache.Contains(cacheKey) == true) { var content = _cache.Get<AjaxResult>(cacheKey); }