I am implementing Sitecore 8 Web Api. To be exact, i am using ServiceApiController in Sitecore Services Infrastructre. I wonder how can I cache the JSON output from this controller in such a way that it gets updated only if the lucene index which I am fetching data from, gets rebuilt?
I have not registered this controller as controller rendering because apparently we don't need to do that and it just works out-of-box. I just read the JSON output by an ajax call through jQuery and the javascript code and HTML markup is inside a MVC view rendering. I guess it doesn't make sense to setup cache on the view rendering. Isn't it?
What should i do?
The best option would be to use the HtmlCache and store the data there. This cache gets completed cleared on a publish, so it would make sense to use it.
You can add an entry into the cache by using the SetHtml
method:
var cache = Sitecore.Caching.CacheManager.GetHtmlCache(Sitecore.Context.Site);
var json = cache.GetHtml("mycachekey");
if (string.IsNullOrWhiteSpace(json))
{
var json = // build your json output here
cache.SetHtml("mycachekey", jsonValue);
}
return json;