技术开发 频道

ASP.NET中数据缓存和输出缓存详解

  自定义缓存(Custom Caching)

  你也可以创建自定义的程序来缓存页面。ASP.net提供了一种很便捷的方式来创建自定义缓存,使用VarByCustom属性指定自定义缓存类型的名字。

  你还要创建为缓存生成自定义字符串的方法,如下:

  public override stringGetVaryByCustomString(HttpContext context, stringcustom)
  {
  
if(custom == "browser")
  {
  returncontext.Request.Browser.Browser
+
  context.Request.Browser.MajorVersion;
  }
  
else
  {
  
return base.GetVaryByCustomString(context, custom);
  }
  }

 

  这个方法必须写在global.asax文件中。ASP.NET使用该方法返回的字符串来实现缓存,如果这个方法在不同的请求中返回相同的字符串,ASP.NET就会使用缓存的页面,否则就会生成新的缓存版本。

  上面的例子中GetVaryByCustomString()方法根据浏览器的名字创建缓存字符串,ASP.NET会根据不同的浏览器请求创建不同版本的缓存。

  控件缓存(Control Cache )

  上面的缓存技术可以让你很容易的缓存整个页面,如果要缓存指定控件的内容,可以通过指定VaryByControl 属性来完成。

  %@OutputCacheDuration="20"VaryByControl="MyControl_1"%

 

  上面代码ASP.NET将会缓存MyControl_1控件20分钟。如果要根据一些属性值来缓存控件只需要将OutPutCache指令加入*.ascx页面。

<%@Control Language="C#"AutoEventWireup="true"CodeFile="MyControl.ascx.cs"
Inherits
="Controls_MyControl"%>
<%@OutputCacheDuration="20"VaryByControl="EmployeeID"%>  

  VaryByControl=”EmployeeID”告诉ASP.NET根据控件中声明的EmployeeID属性来创建不同版本的缓存。

  在 .ascx.cs 文件加入EmplyeeID属性为ASP.NET 缓存使用。

  在页面中增加控件并且设置 EmployeeID.

    private int_employeeID;
  
public intEmployeeID
  {
  
get{ return_employeeID; }
  
set{ _employeeID = value; }
  }
  
protected voidPage_Load(objectsender, EventArgs e)
  {
  lblDate.Text
= DateTime.Now.ToShortDateString();
  lblTime.Text
= DateTime.Now.ToLongTimeString();
  lblEmployeeID.Text
= EmployeeID.ToString();
  }

 

     缓存配置文件(Cache Profile )

  Web.config可以配置缓存相关的设置,

  <system.web>
  
<caching>
    
<outputCacheSettings>
      
<outputCacheProfiles>
        
<addname="ProductItemCacheProfile" duration="60"/>
      
</outputCacheProfiles>
    
</outputCacheSettings>
  
</caching>
</system.web>

 

   你可以通过设置 CacheProfile=”ProfileName” 属性 来使用上面的配置:

  %@OutputCacheCacheProfile="ProductItemCacheProfile"VaryByParam="None"%

 

0
相关文章