2010-04-22 12 views
2

我有一個IHttpHandler我想掛鉤到OutputCache支持,因此我可以將緩存的數據卸載到IIS內核。我知道MVC必須以某種方式做到這一點,我發現這OutputCacheAttribute如何使用IHttpHandler啓用OutputCache

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

這是行不通的。如果您嘗試此操作並刷新頁面,則每次刷新都會看到新的時間。 – 2010-04-22 13:50:59

+0

對不起,拿出Response.End – 2010-04-22 14:12:12

+0

這仍然缺少IIS內核緩存(通過perfmon.msc檢查Web服務緩存\內核:URI緩存未命中,Web服務緩存內核:URI緩存命中) – 2010-04-22 14:48:50