ASP.NET 2.0中max-age设置


  本文标签:max-age设置 ASP.NET 2.0

  ASP.NET 2.0中出现的一个bug就是不能改变max-age头  。当max-age设置为0时,ASP.NET 2.0会设置Cache-control为私有,因为max-age= 0意味着不需要缓存  。因此,没有办法能够使得ASP.NET 2.0返回缓存响应的头  。这是由于ASP.NET AJAX框架对Web服务调用进行了拦截并在执行一个请求之前,错误地将max-age设置为0作为默认值  。

  

  1. public string CachedGet2()  
  2. {  
  3. TimeSpan cacheDuration = TimeSpan.FromMinutes(1);  
  4. FieldInfo maxAge = Context.Response.Cache.GetType().GetField("_maxAge",  
  5. BindingFlags.Instance|BindingFlags.NonPublic);  
  6. maxAge.SetValue(Context.Response.Cache, cacheDuration);  
  7. Context.Response.Cache.SetCacheability(HttpCacheability.Public);  
  8. Context.Response.Cache.SetExpires(DateTime.Now.Add(cacheDuration));  
  9. Context.Response.Cache.AppendCacheExtension(  
  10. "must-revalidate, proxy-revalidate");  
  11. return DateTime.Now.ToString();  

  
现在max-age设置成了60,因此浏览器将缓存响应60秒  。如果你在60秒内进行相同的再次调用,则会返回相同的响应  。这里的测试输出展示了从服务器上返回的时间:

一分钟以后,缓存期满同时浏览器再次向服务器发送请求调用  。其客户端代码如下:

  

  1. function testCache()  
  2. {  
  3. TestService.CachedGet(function(result)  
  4. {  
  5. debug.trace(result);  
  6. });  

  
另外一个问题解决了  。在web.config文件中,你会看到ASP.NET Ajax添加了如下节点值:

  

  1. <system.web> 
  2. <trust level="Medium"/> 

  
这可以阻止我们设置Response对象的_maxAge字段,因为它需要反射  。因此,你不得不删除这一信任级别或者将其放置为Full  。

  

  1. <system.web> 
  2. <trust level="Full"/>