We help IT Professionals succeed at work.

C# Cache / API

ITsolutionWizard
on
187 Views
Last Modified: 2019-01-28
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

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION

Author

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

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?