Reputation: 24208
I am developing an application that presents a company's twitter feed on a Facebook application. This is a large company with lots of traffic to the FB App so I need to cache the Twitter data I receive (from the twitter API) so that I can avoid their rate limits.
In my code, I use LinqToTwitter to call the API and then I construct a string of JSON with the results. That string is then fed to the user's browser via AJAX.
The rate limit for Twitter API calls is 150 per hour, so I figure I will just place the string of JSON data I construct in a cache object and only refresh it once per minute leaving me well below the Twitter rate limit.
The problem is that I am fairly new to MVC for .NET and can't seem to use System.Web.Caching like I could do in a webforms application.
In older webforms apps I simply did something like:
private string KeyTwitterData;
...
string data = null;
if (Cache[KeyTwitterData] == null)
{
var url = LinqToTwitter.Request.Url;
data = ServiceMethods.GetConversation(url);
Cache.Insert(KeyTwitterData, data);
}
else
{
data = (string)Cache[KeyTwitterData];
}
Can someone please tell me how to accomplish this in MVC3?
Thanks!
Matt
Upvotes: 10
Views: 7889
Reputation: 1038810
In ASP.NET MVC 3 if you want to cache the result of a controller action you could decorate it with the [OutputCache]
attribute:
[OutputCache(Duration = 3600, Location = OutputCacheLocation.Server, VaryByParam = "none")]
public ActionResult Foo()
{
var model = SomeExpensiveOperationToFetchData();
return View(model);
}
If you don't want to cache the entire output of a controller action you could use the MemoryCache class:
var data = MemoryCache.Default[KeyTwitterData];
if (data == null)
{
data = SomeExpensiveOperationToFetchData();
MemoryCache.Default.Add(KeyTwitterData, data, DateTime.Now.AddMinutes(5));
}
// use the data variable here
Upvotes: 17
Reputation: 3523
Use HttpContext.Cache in your controller
string data = null;
if (HttpContext.Cache[KeyTwitterData] == null)
{
var url = LinqToTwitter.Request.Url;
data = ServiceMethods.GetConversation(url);
HttpContext.Cache.Insert(KeyTwitterData, data);
}
else
{
data = (string)HttpContext.Cache[KeyTwitterData];
}
Upvotes: 1