mvc4中有一个标记属性OutputCache,用来对ActionResult结果进行缓存,如何理解呢?概括地说,就是当你的请求参数没有发生变化时,直接从缓存中取结果,不会再走服务端的Action代码了.

1.[OutputCache(Duration=300)]

//事例代码: 
[OutputCache(Duration = 300)] public ActionResult Index(int? id,string name) { var person = new Person { ID = Convert.ToInt16(id), Name = name, City="Beijing"}; return View(person); }

请求此Action的url可以为:  person/Index?id=100&name="bird",

当第一次请求这个地址时,会执行Index方法,并把结果缓存起来,且过期时间为300秒

接下来,如果不改变id和name参数的前提下,在距离上次请求300秒  内,再来请求这个地址,不会执行Index方法,直接从缓存中拿结果.

当id或者name的参数值发生变化时,发送请求时,会执行index方法,然后再缓存此结果.

[Output(Duration=300)],这种方法没有指明具体针对哪个参数来缓存,所以默认是针对所有参数,即任何一个参数值发生变化,都会缓存一份.

那么,如果,我想指定具体的参数,进行缓存该如何做呢?请看下一个方案

2.[OutputCache(Duration = 300,VaryByParam="id")]

此种方式,指明了缓存是针对哪个参数来做的,即只有当id参数值发生变化的时候,才做缓存,其他机制同第一种.

 

3.对于参数中的缓存时间设置,可以在配置文件中进行配置.

 <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="long" duration="50"/>
          <add name="Short" duration="10"/>
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>

使用:

  [OutputCache(CacheProfile="Short", VaryByParam = "id")]
        public ActionResult Index(int? id, string name)
        {
            var person = new Person { ID = Convert.ToInt16(id), Name = name, City = "Beijing" };
            return View(person);
        }

如此,便于维护和更改.

 

posted on 2016-01-12 10:55  青松之林  阅读(4521)  评论(0编辑  收藏  举报