当用户访问页面时,整个页面将会被服务器保存在内存中,这样就对页面进行了缓存。当用户再次访问该页,页面不会再次执行数据操做,页面首先会检查服务器中是否存在缓存,若是缓存存在,则直接从缓存中获取页面信息,若是页面不存在,则建立缓存。json
页面输出缓存适用于那些数据量较多,而不会进行过多的事件操做的页面,若是一个页面须要执行大量的事件更新,以及数据更新,则并不能使用页面输出缓存。缓存
一般咱们在缓存aspx页面的时候,能够页面经过以下设置服务器
<%@ OutputCache Duration="120" VaryByParam="paramName" %>app
上述代码使用@OutputCatch指令声明了页面缓存,该页面将被缓存120秒。@OutputCatch指令包括10个属性,经过这些属性可以分别为页面的不一样状况进行缓存设置,经常使用的属性以下所示:ide
CacheProfile:获取或设置OutputCacheProfile名称。性能
Duration:获取或设置缓存项须要保留在缓存中的时间。ui
VaryByHeader:获取或设置用于改变缓存项的一组都好分隔的HTTP标头名称。spa
Location:获取或设置一个值,该值肯定缓存项的位置,包括Any、Clint、Downstream、None、Server和ServerAndClient。默认值为Any。code
VaryByControl:获取或设置一簇分好分隔的控件标识符,这些标识符包含在当前页或用户控件内,用于改变当前的缓存项。blog
NoStore:获取或设置一个值,该值肯定是否设置了“Http Cache-Control:no-store”指令。
VaryByCustom:获取输出缓存用来改变缓存项的自定义字符串列表。
Enabled:获取或设置一个值,该值指示是否对当前内容启用了输出缓存。
VaryByParam:获取查询字符串或窗体POST参数的列表。
对于aspx页面来讲,很是简单。那么在ashx页面中,咱们又该如何设页面缓存呢?
直接上代码,以下:
public class autocomp : IHttpHandler { public void ProcessRequest(HttpContext context) { OutputCachedPage page = new OutputCachedPage(new OutputCacheParameters { Duration = 120, Location = OutputCacheLocation.Any, VaryByParam = "paramName" }); page.ProcessRequest(HttpContext.Current); context.Response.ContentType = "application/json"; context.Response.BufferOutput = true; var searchTerm = (context.Request.QueryString["paramName"] + "").Trim(); context.Response.Write(searchTerm); context.Response.Write(DateTime.Now.ToString("s")); } public bool IsReusable { get { return false; } } private sealed class OutputCachedPage : Page { private OutputCacheParameters _cacheSettings; public OutputCachedPage(OutputCacheParameters cacheSettings) { // Tracing requires Page IDs to be unique. ID = Guid.NewGuid().ToString(); _cacheSettings = cacheSettings; } protected override void FrameworkInitialize() { base.FrameworkInitialize(); InitOutputCache(_cacheSettings); } } }
若是Query String多个查询参数,注意查看VaryByParam
public class test : IHttpHandler { public void ProcessRequest(HttpContext context) { OutputCachedPage page = new OutputCachedPage(new OutputCacheParameters { Duration = 120, Location = OutputCacheLocation.Server, VaryByParam = "name;city" }); page.ProcessRequest(HttpContext.Current); context.Response.ContentType = "application/json"; context.Response.BufferOutput = true; var searchTerm = (context.Request.QueryString["name"] + "").Trim(); var searchTerm2 = (context.Request.QueryString["city"] + "").Trim(); context.Response.Write(searchTerm+" "+searchTerm2+" "); context.Response.Write(DateTime.Now.ToString("s")); } public bool IsReusable { get { return false; } } private sealed class OutputCachedPage : Page { private OutputCacheParameters _cacheSettings; public OutputCachedPage(OutputCacheParameters cacheSettings) { // Tracing requires Page IDs to be unique. ID = Guid.NewGuid().ToString(); _cacheSettings = cacheSettings; } protected override void FrameworkInitialize() { base.FrameworkInitialize(); InitOutputCache(_cacheSettings); } } }