简体   繁体   English

在ASP.NET Web Pages / WebMatrix项目中启用输出缓存

[英]Enabling output caching in ASP.NET Web Pages/WebMatrix projects

I have a simple site that I want to enable output caching for, but it uses ASP.NET Web Pages ( http://asp.net/web-pages , not Web Forms or MVC). 我有一个要为其启用输出缓存的简单站点,但是它使用ASP.NET网页( http://asp.net/web-pages ,而不是Web Forms或MVC)。 Any guidance? 有指导吗?

You can put this at the top of any page you want to cache on the server: 您可以将其放在要在服务器上缓存的任何页面的顶部:

Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams.IgnoreParams = true;

Of, if you want to cache all pages in a folder, put the code in a _PageStart file. 其中,如果要将所有页面缓存在文件夹中,请将代码放在_PageStart文件中。

More information on MSDN: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cache.aspx 有关MSDN的更多信息: http : //msdn.microsoft.com/zh-cn/library/system.web.httpresponse.cache.aspx

The following code does everything you need, and has several overloads to fine tune your output cache for a given page: 以下代码可满足您的所有需求,并具有多个重载以微调给定页面的输出缓存:

@{
    var seconds = 600; //10min
    Response.OutputCache(seconds);
}

Behind the scenes, this is an extension method contained in System.Web.WebPages.dll assembly that do this: 在幕后,这是System.Web.WebPages.dll程序集中包含的扩展方法,它可以执行以下操作:

internal static void OutputCache(HttpContextBase httpContext, HttpCachePolicyBase cache, int numberOfSeconds, bool sliding, IEnumerable<string> varyByParams, IEnumerable<string> varyByHeaders, IEnumerable<string> varyByContentEncodings, HttpCacheability cacheability)
{
  cache.SetCacheability(cacheability);
  cache.SetExpires(httpContext.Timestamp.AddSeconds((double) numberOfSeconds));
  cache.SetMaxAge(new TimeSpan(0, 0, numberOfSeconds));
  cache.SetValidUntilExpires(true);
  cache.SetLastModified(httpContext.Timestamp);
  cache.SetSlidingExpiration(sliding);
  if (varyByParams != null)
  {
    foreach (string index in varyByParams)
      cache.VaryByParams[index] = true;
  }
  if (varyByHeaders != null)
  {
    foreach (string index in varyByHeaders)
      cache.VaryByHeaders[index] = true;
  }
  if (varyByContentEncodings == null)
    return;
  foreach (string index in varyByContentEncodings)
    cache.VaryByContentEncodings[index] = true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM