ASP.NET MVCでキャッシュについて。
出力キャッシュ、ブラウザキャッシュ、MemoryCache。
出力キャッシュ
[HttpGet]
[OutputCache(Duration = 600, VaryByParam = "foo")] /// 10分
public ActionResult SampleAction(string foo, int bar) {
条件で出力キャッシュを無効にする
[HttpGet]
[OutputCache(Duration = 600, VaryByParam = "foo")] /// 10分
public ActionResult SampleAction(string foo, int bar) {
if (foo == "hoge") {
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
出力キャッシュを削除する
public ActionResult InvalidateCacheForSampleAction()
{
var path = Url.Action("SampleAction");
Response.RemoveOutputCacheItem(path);
ChildActionの出力キャッシュ
これでViewの@Html.Action("SampleChildAction")
の部分がキャッシュされます。
[HttpGet]
[ChildActionOnly]
[OutputCache(Duration = 600)] /// 10分
public ActionResult SampleChildAction() {
ブラウザのキャッシュ
以下はブラウザのキャッシュを無効にする例です。
[HttpGet]
public ActionResult SampleAjaxAction()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
var obj = new
{
Message = "hoge",
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
MemoryCache
MemoryCacheを使うには「参照の追加」で「System.Runtime.Caching」アセンブリへの参照を追加しておく必要があります。
var cache = MemoryCache.Default;
var policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(10);
cache.Add(new CacheItem("sampleCacheKey", cachedObj), policy);