Asp.Net MVC 添加和更新頁面緩存

1. 添加頁面緩存


添加頁面緩存非常容易

[OutputCache( Duration=6000)]
public ActionResult CachePage()
{
	// Do something

	return 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();
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章