4

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):

  1. User enters search parameters

  2. Try { LINQ Query to select results from a List }

  3. 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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So instead of using an List<MyObject> I should use the Cache class and add MyObject items to the Cache with a Key of "param1-param2-param3" etc?
@Steve yeah, that's how I'd do it/have done similar things in the past.
Thanks Rob - how would I access the Cache objecte? something like: if if (System.Web.HttpContext.Current.Cache["test"] == null){ //get data from web service} else{ return object }
@steve that would work, take a look at the cache docs.
1

You may want to look at built-in ASP.NET MVC output caching capabilities described, for example, in this tutorial.

Short version:

Just add [OutputCache(Duration=%duration_in_seconds%, VaryByParam="none")] attribute to MVC method for which you want to cache the results.

1 Comment

I'm not looking at caching the output of the controller - the controller calls an external web service - i want to cache the results of that external call so that my controller doesn't need to keep calling the external service

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.