【问题标题】:In memory caching in ASP.NET MVC 5 is not working在 ASP.NET MVC 5 中的内存缓存不起作用
【发布时间】:2016-09-26 12:17:44
【问题描述】:

我正在开发一个 ASP.NET MVC 项目。在我的项目中,我正在对一些数据进行内存缓存以获得更好的性能。我对内存缓存的理解是它在服务器上缓存数据,所以无论客户端是谁,在下一个请求中,它从缓存而不是从数据库加载数据,然后发送回客户端。我在 ASP.NET MVC 5 中进行内存缓存,但它不起作用。

这是我正在缓存的 GetRegions 方法:

public IEnumerable<Region> GetRegions(){
    ObjectCache cache = MemoryCache.Default;
    if(cache.Get("regions")==null)
    {
        IEnumerable<Region> regions = db.Regions;
        cache.Add("regions", regions, DateTime.Now.AddDays(1));
        return regions;
    }
    else
    {
        IEnumerable<Region> regions = (IEnumerable<Region>)cache.Get("regions");
        return regions;
    }
}

根据上面的代码,在第一个请求中cache.Get("regions") 将是空的。但在第二个请求中,它不应该为空。但每当我访问该方法时,cache.Get("regions") 始终为空。我在内存缓存中的做法是否正确?

【问题讨论】:

    标签: asp.net-mvc caching memorycache


    【解决方案1】:

    您拥有的代码应该可以工作,尽管它并不完全正确(它使缓存在检查和使用之间过期的可能性很小),但由于您的过期时间很长,我怀疑这不是正在发生的事情这里。要更正您的代码:

    public IEnumerable<Region> GetRegions()
    {
        ObjectCache cache = MemoryCache.Default;
        const string key = "regions";
    
        IEnumerable<Region> regions = cache.Get(key) as IEnumerable<Region>;
        if (regions == null)
        {
            regions = db.Regions;
            cache.Add(key, regions, DateTime.Now.AddDays(1));
        }
        return regions;
    }
    

    我不确定这是否能解决您的问题!

    【讨论】:

    • 我使用断点检查。但它不起作用。我所做的是作为第一个请求从 Firefox 访问。它是空的。然后我打开 chrome 并提出第二个请求。当我用 chrome 发出第二个请求时,它仍然为空。实际上它不应该为空。对吗?
    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2019-05-16
    • 2016-06-24
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    相关资源
    最近更新 更多