ASP.NET MVC Caching & Renew Caching Item
\Views\Home\Index.cshtml |
<form id="Form" action="\Home\ClearCache" method="post"> < div >@(ViewBag.Cache1)</ div > < div >@(ViewBag.Cache2)</ div > < div >< input type="submit" value="Clear Cache 2" /><</div> </form> |
\Controllers\HomeController.cs |
using System; using System.Web; using System.Web.Mvc; using System.Runtime.Caching; namespace MVCApplicationCaching.Controllers { public class HomeController : Controller { private ObjectCache cache; public HomeController() { this.cache = MemoryCache.Default; } public ActionResult Index() { if (this.cache["Cache1"] == null) this.cache.Set("Cache1", System.DateTime.Now.ToLongTimeString(), getCacheItemPolicy(10)); if (this.cache["Cache2"] == null) this.cache.Set("Cache2", System.DateTime.Now.ToLongTimeString(), getCacheItemPolicy(10)); ViewBag.Cache1 = this.cache["Cache1"].ToString(); ViewBag.Cache2 = this.cache["Cache2"].ToString(); return View(); } [HttpPost] public ActionResult ClearCache(FormCollection coll) { this.cache.Remove("Cache2"); return RedirectToAction("Index"); } private CacheItemPolicy getCacheItemPolicy(int ExpiryTimeSec) { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(ExpiryTimeSec); return policy; } } } |