How to cache web service results in C # / MVC and not call a web service all the time

I am creating a small web application that will essentially be used to call an external REST / JSON web service, passing some parameters and returning the results of this to the user in a table.

I know that the data from this external service will not change often (perhaps once a day), and I want to call the web service many times over for the same request.

What would be a good way to implement some kind of caching?

At the moment, I have compiled something (which works, but I don't think this is the right way):

  • User enters search parameters

  • Try {LINQ Query to select results from the list}

  • Catch {Call the web service, fill out the results list, and then rerun the LINQ query. If there are still no results, then throw an exception}

I think I would clear the List at the end of the day so that it is rebuilt every day.

The code is a bit dirty, but it seems to work most of the time - is there a better way to achieve this?

+4
source share
2 answers

You probably want to use one of the existing caching classes that will handle expiration policies for you, for example. System.Web.HttpContext.Current.Cache. You can create cache keys from your request parameters and first look for it in the cache. If there is no data, you can call the web service and add the results to the cache with an absolute expiration of, say, 12 hours - if the results still do not throw your exception.

If you use .Net 4, then in the System.Runtime.Caching namespace there are additional caching options or there is a caching application block in the Enterprise Library that you can look at.

+4
source

You can see the built-in ASP.NET MVC output caching features described, for example, in this guide .

Short version:

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

+1
source

All Articles