Link to home
Start Free TrialLog in
Avatar of ITsolutionWizard
ITsolutionWizardFlag for United States of America

asked on

C# Cache / API

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;
        }
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ITsolutionWizard

ASKER

can you suggest what we should do? I do not know what you mean by 'service layer'
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.
can you send me some suggestions in code?