Пример #1
0
        /// <summary>
        /// 将action内产生的所有输出数据进行缓存
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="key">缓存key</param>
        /// <param name="action">产生输出的方法</param>
        /// <param name="timeout">超时时间</param>
        public static void CachePartial(this MyCache cache, string key, Action action, DateTime timeout)
        {
            HttpContext context = HttpContext.Current;

            if (context == null)
            {
                throw new InvalidOperationException("不存在的http上下文");
            }

            var response = context.Response;

            byte[] cacheBuffer = cache.Get <byte[]>(key, () =>
            {
                //清空掉缓冲区的数据
                var fr   = new FilchResponFilter(response.Filter);
                fr.Filch = true;

                response.Flush();
                response.Filter = fr; //通过过滤器准备窃取action产生的输出数据
                action();
                response.Flush();     //再次刷新缓冲区以便将action所有产生数据窃取
                var bs   = fr.FilchBytes();
                fr.Filch = false;

                return(bs);
            }, timeout);

            if (cacheBuffer != null && cacheBuffer.Length > 0)
            {
                response.OutputStream.Write(cacheBuffer, 0, cacheBuffer.Length);
            }
        }
Пример #2
0
        /// <summary>
        /// 将action内产生的所有输出数据进行缓存
        /// </summary>
        /// <param name="cache"></param>
        /// <param name="key">缓存key</param>
        /// <param name="action">产生输出的方法</param>
        /// <param name="timeout">超时时间</param>
        public static void CachePartial(this MyCache cache, string key, Action action, DateTime timeout)
        {
            HttpContext context = HttpContext.Current;
            if (context == null)
                throw new InvalidOperationException("不存在的http上下文");

            var response = context.Response;
            byte[] cacheBuffer = cache.Get<byte[]>(key, () =>
            {
                //清空掉缓冲区的数据
                var fr = new FilchResponFilter(response.Filter);
                fr.Filch = true;

                response.Flush();
                response.Filter = fr;   //通过过滤器准备窃取action产生的输出数据
                action();
                response.Flush();   //再次刷新缓冲区以便将action所有产生数据窃取
                var bs = fr.FilchBytes();
                fr.Filch = false;

                return bs;

            }, timeout);

            if (cacheBuffer != null && cacheBuffer.Length > 0)
            {
                response.OutputStream.Write(cacheBuffer, 0, cacheBuffer.Length);
            }

        }