C# Cache / API

ITsolutionWizard
ITsolutionWizard used Ask the Experts™
on
I have mvc / c# / razor app that using the following method / class and I found out our developer put this on Views/Shared/Layoutpage.
It looks like it is called this method everytime when the page is refreshed. As a result, it is super easy to max out the API usage.

My question is: What is the best practice to use cache in c# to reduce this usage? In general, the layoutpage will be loaded as usual.
Please show me how it works in codes/c#. Thanks

 public static string GetLatitiudeByIP(string ip)
        {
            string returnValue = "34.028623";
            XmlDocument foo = new XmlDocument();
            foo.Load(String.Format("http://api.ipstack.com/" + ip + "?access_key=7efaasdfasdfasdfadsf3829ad25d56ab30492c9c79d24f1&output=xml&legacy=1"));
            XmlNode latitudeNode = foo.SelectSingleNode("/result/latitude");
            if(latitudeNode != null)
            {
                returnValue = latitudeNode.InnerText;
            }
            return returnValue;
        }
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
IMO, why is this even in the view? I would move this logic to a service layer where you can share the code between disparate projects.

Next, what exactly do you want to cache? You'll need to figure out how long you want whatever that is cached (i.e. figure out a cache invalidation process). Keep in mind that the more you cache, the more memory you consume on your server.

Author

Commented:
can you suggest what we should do? I do not know what you mean by 'service layer'
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Extending the previous comment, caching is great so long as cache data avoids becoming stale...

In other words, your cached value becomes old + the actual data has changed.

For caching, you just have to ensure you expire your cache at a rate faster than actual API data changes, so you make API calls when required, to actually pull truly new data.

For GEO coordinates, likely this data will change very infrequently, so caching this data to reduce API calls will likely be good + have few problems with data differences between your cache + API you're calling.

Author

Commented:
can you send me some suggestions in code?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial