Hello
I have created a web API A that get some JSon data from another Web API B
I want to cache this Json data on my web API A as the data from B will not change frequently and that lot's of call will be done on the WEB API A to get this Json data.
So I have implemented Cache on the server like below:
public async Task<HttpResponseMessage> getFedCustomers() { try { using (var client = new HttpClient()) { HttpResponseMessage response = null; var cacheKey = "fedcache"; var cTime = DateTime.Now.AddMinutes(double.Parse(ConfigurationManager.AppSettings["CacheDelayInMinute"])); var cExp = System.Web.Caching.Cache.NoSlidingExpiration; var cPri = System.Web.Caching.CacheItemPriority.Normal; string responseBody = ""; JavaScriptSerializer Jser = new JavaScriptSerializer(); if (HttpContext.Current.Cache[cacheKey] == null) { client.BaseAddress = new Uri(ConfigurationManager.AppSettings["IntegrationServiceBaseAddressURI"]); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); response = await client.GetAsync(ConfigurationManager.AppSettings["FedListURI"]); response.EnsureSuccessStatusCode(); // Throw if not a success code. responseBody = await response.Content.ReadAsStringAsync(); var test = Jser.DeserializeObject(responseBody); HttpContext.Current.Cache.Insert(cacheKey, test, null, cTime, cExp, cPri, null); } else { var CacheBody = HttpContext.Current.Cache[cacheKey]; response = this.Request.CreateResponse(HttpStatusCode.OK, CacheBody, "application/json"); } return response; } } catch (Exception ex) { string errorMsg = ""; if (ex.InnerException != null) { if (!string.IsNullOrWhiteSpace(ex.InnerException.Message)) { errorMsg = string.Format(ConfigurationManager.AppSettings["ProcessFailed"], "getFedCustomers", ex.InnerException.Message); } else { errorMsg = string.Format(ConfigurationManager.AppSettings["ProcessFailed"], "getFedCustomers", ex.Message); } } else { errorMsg = string.Format(ConfigurationManager.AppSettings["ProcessFailed"], "getFedCustomers", ex.Message); } return Request.CreateResponse(HttpStatusCode.BadRequest, errorMsg, "application/json"); } }
Cache seems to work properly but on client side I never know if data comes from cache or the call to the Web API B.
I have tried to set the HttpStatusCode.NotModified in the else when we return cache data but no data are returned in that case.
I want that all clients get the same data from the server, so if data is in cache it will be cache data otherwise a call will be done to the web api B.
I have also tried to implement [CacheOutput( ServerTimeSpan = 60)] Strathweb.CacheOutput.WebAPi2 but looking at fiddler each user start by a requestStatus 200 then 304. I should expect the first one at 200 and the other at 304 due to the delay that I set to some minutes.