开发者

How to enable OutputCache with an IHttpHandler

I have an IHttpHandler that I would like to hook into the OutputCache support so I can offload cached data to the IIS kernel. I know MVC must do this somehow, I found this in OutputCacheAttribute:

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

But not sure how to apply this to an IHttpHandler. Tried something like this, but of course this doesn't work:

public class CacheTest : IHttpHandler
{
    public void开发者_JAVA百科 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;
        }
    }
}


It has to be done like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜