15
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET MVCでキャッシュ

Last updated at Posted at 2014-02-06

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);
15
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?