ASP .Net MVC 5 JsonResult caching

后端 未结 1 1681
旧巷少年郎
旧巷少年郎 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 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 newItems = repository.GetCategories();
                cache.Set(categoryCacheKey, newItems, policy);
                return newItems;
            }
            else
            {
                return (List) items;
            }
        }
    }
    

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

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