How to programmatically clear outputcache for controller action method

Solution 1:

Try this

var urlToRemove = Url.Action("AjaxHtmlOutputMethod", "Controller");
HttpResponse.RemoveOutputCacheItem(urlToRemove);

UPDATED:

var requestContext = new System.Web.Routing.RequestContext(
    new HttpContextWrapper(System.Web.HttpContext.Current),
    new System.Web.Routing.RouteData());

var Url = new System.Web.Mvc.UrlHelper(requestContext);

UPDATED:

Try this:

[OutputCache(Location= System.Web.UI.OutputCacheLocation.Server, Duration=3600,VaryByParam="param1;param2")]

Otherwise the cache deletion won't work because you've cached the HTML output on the user's machine

Solution 2:

Further to the accepted answer, to support VaryByParam parameters:

  [OutputCache (Duration=3600, VaryByParam="param1;param2", Location = OutputCacheLocation.Server)]
  public string AjaxHtmlOutputMethod(string param1, string param2)
  {
       object routeValues = new { param1 = param1, param2 = param2 };

       string url = Url.Action("AjaxHtmlOutputMethod", "Controller", routeValues);

       Response.RemoveOutputCacheItem(url);
  }

However Egor's answer is much better, because it supports all OutputCacheLocation values:

  [OutputCache (Duration=3600, VaryByParam="param1;param2")]
  public string AjaxHtmlOutputMethod(string param1, string param2)
  {
       if (error)
       {
           Response.Cache.SetNoStore(); 
           Response.Cache.SetNoServerCaching();
       }
  }

When SetNoStore() and SetNoServerCaching() are called, they prevent the current Request being cached. Further requests will be cached, unless the functions are called for those requests as well.

This is ideal for handling error situations - when normally you want to cache responses, but not if they contain error messages.

Solution 3:

I think correct flow is:

filterContext.HttpContext.Response.Cache.SetNoStore()

Solution 4:

Add code to AjaxHtmlOutputMethod

HttpContext.Cache.Insert("Page", 1);
Response.AddCacheItemDependency("Page");

To clear output cache you can now use

HttpContext.Cache.Remove("Page");