I have an ASP.NET MVC 3 app that is basically just a set of web services. These web services are exposed by a set of Controller actions. Each controller action queries my database. Because my data rarely changes, and, stale data is not a concern, I thought i would implement some cacheing to improve performance. My goals are:
Does that make sense? I know how to prevent the response from caching. I just use the following:
HttpContext.Response.Cache.SetCacheability(cacheability)
However, I'm not sure how to cache my database records in memory for up to 24 hours. Does anyone have any suggestions on how to do this? I'm not even sure where to look.
Thank you
ASP.NET Core API. Caching means to store something in memory that is being used frequently to provide better performance. We will see how you can dramatically improve the performance of an ASP.NET MVC application by taking advantage of the output cache.
Store data into Cache in ASP.NET MVC in ASP.NET MVC Above action method first checks for the null value in HttpContext. Cache[“MyDate”] and it its null then saves current date in the Cache. Next line simply keep the data from the Cache into ViewBag. DateTime.
Any (Default)- Content is cached in three locations- the Web Server, any proxy Servers and the Web Browser. Client- Content is cached on the Web Browser. Server- Content is cached on the Web Server. ServerAndClient- Content is cached on the Web Server and the Web Browser.
L1 cache, or primary cache, is extremely fast but relatively small, and is usually embedded in the processor chip as CPU cache. L2 cache, or secondary cache, is often more capacious than L1.
You can use the System.Runtime.Caching
namespace (or the ASP.NET cache, but this is older and can only be used within web applications).
Here's a sample function which you can use to wrap around your current data retrieval mechanism. You can alter the parameters in MemoryCache.Add to control how much it's cached, but you requested 24h above.
using System.Runtime.Caching; // At top of file
public IEnumerable<MyDataObject> GetData()
{
IEnumerable<MyDataObject> data = MemoryCache.Default.Get(MYCACHEKEY) as IEnumerable<MyDataObject>;
if (data == null)
{
data = // actually get your data from the database here
MemoryCache.Default.Add(MYCACHEKEY, data, DateTimeOffset.Now.AddHours(24));
}
return data;
}
As mentioned by @Bond, you may also wish to look at using an SQL Cache Dependency if the data you're caching is likely to change within the 24 hours. If it's pretty static though, this will do what you asked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With