I am trying to cache a parameterized GET
webservice call in ASP.NET 4.5/C#. I've tried all the options that I've read in StackOverflow, including setting the HttpCachePolicy, using CacheDuration attribute, but I always get Cache-Control :no-cache
, Expired: -1
, Pragma: no-cache
and the call to the webservice returns 200 not 304 (Not modified).
The content is cached correctly on the server,but I want the cache headers to be updated as well so it won't even get to call to the server for a give amount of time which I specified in the cache.
I also tried this approach but it didn't work:
HttpCachePolicy cache = HttpContext.Current.Response.Cache;
cache.VaryByParams["*"] = true;
cache.SetCacheability(HttpCacheability.Private);
cache.SetExpires(DateTime.Now.AddSeconds((double)900));
FieldInfo maxAgeField = cache.GetType().GetField(
"_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);
maxAgeField.SetValue(cache, new TimeSpan(0, 0, 900));
and also tried:
private void SetCachingPolicy()
{
HttpCachePolicy cache = HttpContext.Current.Response.Cache;
cache.VaryByParams["*"] = true;
cache.SetCacheability(HttpCacheability.Private);
cache.SetExpires(DateTime.Now.AddSeconds((double)900));
FieldInfo maxAgeField = cache.GetType().GetField(
"_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);
maxAgeField.SetValue(cache, new TimeSpan(0, 0, 900));
}
The caching code is applied within the web-service call Web Method.
I want the webservice call (which I call from jQuery/Ajax) to be cached in the client for a few seconds or minutes.
I am testing it in my local IIS 7.5 server on my Windows 7 computer, using Visual Studio as the dev platform. I am also using Chrome Network traffic to test the response headers.