How to use caching in ASP.NET Web API?

后端 未结 4 1190
别那么骄傲
别那么骄傲 2020-12-01 02:41

I am using ASP.NET MVC 4 with WEB API

I have the following action, in the action shown below, my service method makes a db call to DoMagic() method and

4条回答
  •  日久生厌
    2020-12-01 03:16

    Add a reference to System.Runtime.Caching in your project. Add a helper class :

    using System;
    using System.Runtime.Caching;
    
    
    public static class MemoryCacher
    {
        public static object GetValue(string key)
        {
            MemoryCache memoryCache = MemoryCache.Default;
            return memoryCache.Get(key);
        }
    
        public static bool Add(string key, object value, DateTimeOffset absExpiration)
        {
            MemoryCache memoryCache = MemoryCache.Default;
            return memoryCache.Add(key, value, absExpiration);
        }
    
        public static  void Delete(string key)
        {
            MemoryCache memoryCache = MemoryCache.Default;
            if (memoryCache.Contains(key))
            {
                memoryCache.Remove(key);
            }
        }
    }
    

    Then from your code get or set objects in the cache :

    list = (List )MemoryCacher.GetValue("CacheItem1");
    

    and

    MemoryCacher.Add("CacheItem1", list, DateTimeOffset.UtcNow.AddYears(1));
    

提交回复
热议问题