2010-04-22 5 views
2

У меня есть IHttpHandler, который я хотел бы подключить к поддержке OutputCache, чтобы я мог загружать кэшированные данные в ядро ​​IIS. Я знаю, что MVC должен сделать это каким-то образом, я нашел это в OutputCacheAttribute:Как включить OutputCache с IHttpHandler

public override void OnResultExecuting(ResultExecutingContext filterContext) { 
     if (filterContext == null) { 
      throw new ArgumentNullException("filterContext"); 
     } 

     // we need to call ProcessRequest() since there's no other way to set the Page.Response intrinsic 
     OutputCachedPage page = new OutputCachedPage(_cacheSettings); 
     page.ProcessRequest(HttpContext.Current); 
    } 

    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() { 
      // when you put the <%@ OutputCache %> directive on a page, the generated code calls InitOutputCache() from here 
      base.FrameworkInitialize(); 
      InitOutputCache(_cacheSettings); 
     } 
    } 

Но не знаете, как применить это к IHttpHandler. Пытался что-то вроде этого, но, конечно, это не работает:

public class CacheTest : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     OutputCacheParameters p = new OutputCacheParameters { Duration = 3600, Enabled = true, VaryByParam = "none", Location = OutputCacheLocation.Server }; 
     OutputCachedPage page = new OutputCachedPage(p); 
     page.ProcessRequest(context); 

     context.Response.ContentType = "text/plain"; 
     context.Response.Write(DateTime.Now.ToString()); 
     context.Response.End(); 

    } 

    public bool IsReusable 
    { 
     get 
     { 
      return true; 
     } 
    } 
} 

ответ

1

Это должно быть сделано так:

public class CacheTest : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     TimeSpan expire = new TimeSpan(0, 0, 5, 0); 
     DateTime now = DateTime.Now; 
     context.Response.Cache.SetExpires(now.Add(expire)); 
     context.Response.Cache.SetMaxAge(expire); 
     context.Response.Cache.SetCacheability(HttpCacheability.Server); 
     context.Response.Cache.SetValidUntilExpires(true); 

     context.Response.ContentType = "text/plain"; 
     context.Response.Write(DateTime.Now.ToString()); 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return true; 
     } 
    } 
} 
+0

Это не работает. Если вы попробуете это и обновите страницу, вы увидите новое время с каждым обновлением. –

+0

Извините, вытащите Response.End –

+0

Это все еще не хватает кеша IIS (проверка через кеш веб-службы perfmon.msc \ Kernel: пропуски кэша URI, кеш веб-сервиса \ ядро: кеширование URI) –

Смежные вопросы