Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically clear outputcache for controller action method

If the controller action has the OutputCache attribute specified on an action, is there any way to clear the output cache without having to restart IIS?

[OutputCache (Duration=3600,VaryByParam="param1;param2")] public string AjaxHtmlOutputMethod(string param1, string param2) {   var someModel = SomeModel.Find( param1, param2 );    //set up ViewData   ...    return RenderToString( "ViewName", someModel ); } 

I'm looking at using HttpResponse.RemoveOutputCacheItem(string path) to clear it, but I'm having trouble figuring out what the path should be to map it to the action method. I'm going to try again with the aspx page that is rendered by ViewName.

Possibly I'll just manually insert the output of RenderToString into the HttpContext.Cache instead if I can't figure this one out.

Update

Please note that the OutputCache is VaryByParam, and testing out a hardcoded path "/controller/action" does not actually clear the outputcache, so it looks like it has to match "/controller/action/param1/param2".

That means I'll probably have to revert to object level caching and manually cache the output for RenderToString() :(

like image 860
marcel_g Avatar asked Jul 22 '09 20:07

marcel_g


People also ask

What is Varybyparam Outputcache?

It allows varying the cached output by GET query string or form POST parameters. For instance, you can vary the user-control output to the cache by specifying the user-control name along with either a query string or a form POST parameter. For more information, see Caching Multiple Versions of User Control Output.

What is Outputcache?

The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.


1 Answers

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

like image 158
eu-ge-ne Avatar answered Sep 19 '22 09:09

eu-ge-ne