Avatar of ITsolutionWizard
ITsolutionWizard
Flag 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;
        }
ASP.NETC#

Avatar of undefined
Last Comment
ITsolutionWizard

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
kaufmed

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ITsolutionWizard

ASKER
can you suggest what we should do? I do not know what you mean by 'service layer'
David Favor

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.
ITsolutionWizard

ASKER
can you send me some suggestions in code?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck