简体   繁体   中英

ASP.NET MVC: Increment counter on controller, being cached

The controller is:

[OutputCache(Duration = Int32.MaxValue, VaryByParam = "id", SqlDependency = "data:table")]
public ActionResult Details(int id)
{
   var model = repo.GetDetails(id);
   repo.IncreaseCounter(id);
   return View(model);
}

Of cause counter doesn't work as it supposed to (increase counter when someone open the page).

Is it possible to call repo.IncreaseCounter(id) every time but caching leave enabled?

i think, i could call two controllers: one to increase counter, and this one. Could you advise more elegant way? TIA

One option is to use an image based tracker inside each page:

<img src="/counter/increase/12" />

and then setup a controller action which will increase the counter:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = OutputCacheLocation.None)]
public ActionResult Increase(int id)
{
    repo.IncreaseCounter(id);
    return File("empty.png", "image/png");
}

As an alternative to image based tracker you could use an AJAX based tracker which will hit the controller action using AJAX.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM