ASP .Net MVC 5 JsonResult caching

↘锁芯ラ 提交于 2019-12-03 14:08:12

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>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!