zazka
zazka

Reputation: 13

ASP.NET Core cache external web call for X time

I have an WEB API method where in an action method I build a model and 1 of the fields is built from an external API. However speed optimization is important and I want to cache that single request to the external API once X minutes. I am trying to achieve it using HttpClient and Delegating handler but anything else is welcomed.

Upvotes: 1

Views: 738

Answers (1)

OrcusZ
OrcusZ

Reputation: 3660

For me the better solution is to cache the result from your WEB Api in memory cache or distributed cache

Here the implementation I did for distributed cache

    private readonly IDistributedCache _cache;
            public Constructor(IDistributedCache cache)
            {
                _cache = cache;
            }

     public async Task<MyModel> GetWebApiData(double? latitude, double? longitude)
        {    
               var key = $"MyKey";
                var cachedValue = await _cache.GetAsync(key);

                if (cachedValue == null)
                {
                    data = "CallWebApi"
                    await SetDataToCache(key, data);
                }
                else
                {
                    data = JsonConvert.DeserializeObject<MyModel>(Encoding.UTF8.GetString(cachedValue));
                }
}

    public async Task SetDataToCache(string key, MyModel data)
            {
                if (data != null)
                {
                    var json = JsonConvert.SerializeObject(data);
                    await _cache.SetAsync(key, Encoding.ASCII.GetBytes(json), new DistributedCacheEntryOptions()
                    {
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
                    });
                }
            }

Upvotes: 1

Related Questions