How to cache data in a MVC application

后端 未结 14 1280
鱼传尺愫
鱼传尺愫 2020-11-22 11:39

I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.

In my scena

14条回答
  •  不要未来只要你来
    2020-11-22 12:07

    I'm referring to TT's post and suggest the following approach:

    Reference the System.Web dll in your model and use System.Web.Caching.Cache

    public string[] GetNames()
    { 
        var noms = Cache["names"];
        if(noms == null) 
        {    
            noms = DB.GetNames();
            Cache["names"] = noms; 
        }
    
        return ((string[])noms);
    }
    

    You should not return a value re-read from the cache, since you'll never know if at that specific moment it is still in the cache. Even if you inserted it in the statement before, it might already be gone or has never been added to the cache - you just don't know.

    So you add the data read from the database and return it directly, not re-reading from the cache.

提交回复
热议问题