ASP .Net MVC 5 JsonResult caching

后端 未结 1 1682
旧巷少年郎
旧巷少年郎 2021-02-15 20:19

can someone explain me how to implement caching of JsonResult actions in MVC 5 application? I want to use caching of some ajax-called actions using

相关标签:
1条回答
  • 2021-02-15 20:34

    If you want to avoid DB queries, you should consider caching the data at server side. You can use MemoryCache class to do that.

    Quick sample

    public class MyLookupDataCache
    {
        const string categoryCacheKey = "CATEGORYLIST";
        public List<string> GetCategories()
        {
            var cache = MemoryCache.Default;
            var items = cache.Get(categoryCacheKey);
            if (items != null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTime.Now.AddDays(7); //7 days 
                //Now query from db
                List<string> newItems = repository.GetCategories();
                cache.Set(categoryCacheKey, newItems, policy);
                return newItems;
            }
            else
            {
                return (List<string>) items;
            }
        }
    }
    

    You can change the method signature to return the type you want. For simplicity, i am using List<String>

    0 讨论(0)
提交回复
热议问题