失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Asp.Net MVC 添加和更新页面缓存

Asp.Net MVC 添加和更新页面缓存

时间:2021-01-20 03:11:53

相关推荐

Asp.Net MVC 添加和更新页面缓存

1. 添加页面缓存

添加页面缓存非常容易

[OutputCache( Duration=6000)]public ActionResult CachePage(){// Do somethingreturn View();}

2. 更新缓存

如果页面数据发生变化,则需要更新此缓存。此时可使用HttpResponse.RemoveOutputCacheItem("path");

例如:

HttpResponse.RemoveOutputCacheItem(Request.UrlReferrer.LocalPath);

也可以指定某个地址,来清楚更新特定地址的缓存,例如:

Response.RemoveOutputCacheItem("/home/CachePage");

最后附上一段代码,是本人做测试用的。在方法CachePage和CachePage2中加入断点,运行调试,当打开CachePage或CachePage2后,再次刷新,断点不会停留,说明请求并没有进入到action内部。但执行了RemoveCache1后,再次刷新CachePage,代码会停在断点处,说明清除缓存成功。但由于HTTP协议是无状态的,所以说明cache保留在服务器端,而当页面被缓存后,对该页面的请求还是会到IIS服务器,只是没有执行到Action这一层罢了。

代码:

public class HomeController : Controller{public ActionResult Index(string returnUrl){ViewBag.ReturnUrl = returnUrl;return View();}[OutputCache( Duration=6000)]public ActionResult CachePage(){string str = "str";return View();}[OutputCache(Duration = 6000)]public ActionResult CachePage2(){string str = "str";return View();}public ActionResult RemoveCache1(){Response.RemoveOutputCacheItem("/home/CachePage");return View();}}

如果觉得《Asp.Net MVC 添加和更新页面缓存》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。