Search code examples
c#asp.net-mvcweb-serviceswebmethod

Clear the OutputCache of a web service WebMethod


I have a web service containing a method which is cached using CacheDuration:

[WebMethod(CacheDuration = 300)]
public bool CacheTest()
{
    return true;
}

Which is in turn called in an ASP.NET MVC project:

[HttpGet]
public IHttpActionResult Test()
{
    var cacheResult = _testWebService.Test();
    return Ok(cacheResult.ToString());
}

I want to be able to clear the cache for CacheTest, either from within my web service or the ASP.NET MVC project.

I've looked into using HttpResponse.RemoveOutputCacheItem, however, that only seems to clear the cache for the Test controller method and not the CacheTest web service method.

I've also tried using HttpContext.Current.Cache.Remove(), but I do not have a key for the CacheTest cache.


Solution

  • One option would be to reduce the CacheDuration for CacheTest (say to 10 seconds). Then change CacheTest to use a MemoryCache internally, with the cache duration there set to 300 (as it is now).

    When you want to remove an item from the cache, remove it from the MemoryCache. Then, within 10 seconds (or whatever you set the CacheDuration to) your web service will reflect any recent changes.