سؤال

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). Any guidance?

هل كانت مفيدة؟

المحلول 2

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:

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;
}

نصائح أخرى

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.

More information on MSDN: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cache.aspx

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top