Cache individual object in asp.net mvc
Upon writing a controller for exporting image on the fly, I struggled with the problem that: "Output cache does not cache HttpHeader (in this case, "Location" header)". Which lead me to despair since each time i called the controller to output image, it will have to connect to database and do a couple of query, which is not practical in real life. So finally, i found out that i can easily cache objects into a cache provider in Asp.net Mvc. Very useful, all my queries go back to 0 (traced through Ling2sql profiler).
You can use this piece of code in anywhere of your code where you want to cache any object.
(Notice: this code was used in a controller, so I used HttpContext.Cache. But if you use else where that make this code not working, try HttpContext.Current.Cache)
1 2 3 4 5 6 7 8 9 10 | if (HttpContext.Cache["ObjName"] != null) { link = (string)HttpContext.Cache["ObjName"]; return link; } else { HttpContext.Cache.Add("ObjName", link, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(30, 0, 0, 0, 0), System.Web.Caching.CacheItemPriority.High, null); return link; } |
What it did was to check if the ObjName exist in the context, if not, create one and dump the data into it. Remember when you call back from HttpContext, it's an object so you always need a cast. If you don't know about argument, let the intellisense do the work for you.
Time to exand further about the topic: HttpContext.Cache.Add