I’m building a small web application which essentially will be used to call an external REST/JSON Web service, pass some parameters and return the results of this to the user in a table.
I know that the data from this external service will not change often (maybe once a day) and I want to prevent calling the web-service lots of times for the same query.
What would be a good way to implement some sort of caching?
At the moment I put together something (which sort of works, but i don’t think is the correct way):
-
User enters search parameters
-
Try { LINQ Query to select results from a List }
-
Catch { Call the webservice, populate the List with results and then re-run the LINQ query. If still no results again then throw exception}
I guess I would empty the List at the end of the day so each day it will rebuild.
The code is a bit messy but seems to work most of the time – is there any better way to achieve this?
You probably want to use one of the existing caching classes that will handle expiration policies for you e.g. System.Web.HttpContext.Current.Cache. You can create cache keys from your query parameters and first look it up in the Cache. If the data isn’t there, you can call the web service and add the results to the Cache with an absolute expiration of say 12 hours – if there are still no results throw your exception.
If you’re using .Net 4 then there are some additional caching options in the System.Runtime.Caching namespace or there is a caching application block in the Enterprise Library you could look at.