首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用IHttpHandler启用OutputCache

如何使用IHttpHandler启用OutputCache
EN

Stack Overflow用户
提问于 2010-04-22 21:17:08
回答 1查看 997关注 0票数 2

我有一个IHttpHandler,我想把它挂接到OutputCache支持上,这样我就可以把缓存的数据卸载到IIS内核。我知道MVC必须以某种方式做到这一点,我在OutputCacheAttribute中找到了这个。

代码语言:javascript
复制
    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。我尝试过这样的方法,但这当然不起作用:

代码语言:javascript
复制
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;
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2010-04-22 21:40:41

它必须这样做:

代码语言:javascript
复制
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;
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2691080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档