How to "invalidate" parts of the ASP.NET MVC output cache?

Is there a way to programmatically invalidate parts of the ASP.NET MVC output cache? What I would like to do is if the user sends data that changes what will be returned from the cached action, will be able to invalidate the cached data.

Is it possible?

+44
caching asp.net-mvc
Aug 17 '09 at 15:00
source share
2 answers

One way is to use the method:

HttpResponse.RemoveOutputCacheItem("/Home/About"); 

Another way is described here: http://aspalliance.com/668

I think you could implement the second method using the method level attribute for every action you want and just add a line representing the key to it. This is if I understood your question.

Edit: Yes, asp.net mvc OutputCache is just a wrapper.

If you use varyByParam="none" , then you are simply invalid "/Statistics" - this is if <id1>/<id2> are querystring values. This will invalidate all versions of the page.

I did a quick test, and if you add varyByParam="id1" and then create several versions of the page - if you say invalidate invalidate "/Statistics/id1" , this will invalidate this version. But you must continue the tests.

+38
Aug 17 '09 at 18:38
source share

I have done some caching tests. Here is what I found:

You must clear the cache for each route that will lead to your action. If you have 3 routes that lead to the same action in your controller, you will have one cache for each route.

Let's say I have this config route:

 routes.MapRoute( name: "config1", url: "c/{id}", defaults: new { controller = "myController", action = "myAction", id = UrlParameter.Optional } ); routes.MapRoute( name: "Defaultuser", url: "u/{user}/{controller}/{action}/{id}", defaults: new { controller = "Accueil", action = "Index", user = 0, id = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Accueil", action = "Index", id = UrlParameter.Optional } ); 

Then these 3 routes lead to myAction in myController with the myParam parameter:

If my action is as follows

 public class SiteController : ControllerCommon { [OutputCache(Duration = 86400, VaryByParam = "id")] public ActionResult Cabinet(string id) { return View(); } } 

I will have one cache for each route (in this case 3). Therefore, I will have to cancel each route.

Like this

 private void InvalidateCache(string id) { var urlToRemove = Url.Action("myAction", "myController", new { id}); //this will always clear the cache as the route config will create the path Response.RemoveOutputCacheItem(urlToRemove); Response.RemoveOutputCacheItem(string.Format("/myController/myAction/{0}", id)); Response.RemoveOutputCacheItem(string.Format("/u/0/myController/myAction/{0}", id)); } 
0
May 7 '15 at 14:47
source share



All Articles