怎样修改Response中的内容

重写Stream

public class CatchTextStream : Stream
    {
        private Stream output;
        public CatchTextStream(Stream s)
        {
            output = s;
        }
        public override bool CanRead
        {
            get { return output.CanRead; }
        }

        public override bool CanSeek
        {
            get { return output.CanSeek; }
        }

        public override bool CanWrite
        {
            get { return output.CanWrite; }
        }

        public override void Flush()
        {
            output.Flush();
        }

        public override long Length
        {
            get { return output.Length; }
        }

        public override long Position
        {
            get { return output.Position; }
            set { output.Position = value; }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            return output.Read(buffer, offset, count);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return output.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            output.SetLength(value);
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            StringComparison ignore = StringComparison.CurrentCultureIgnoreCase;
            if (HttpContext.Current != null)
            {
                HttpContext context = HttpContext.Current;
                if (context.Response.ContentType.Equals("text/html", ignore))
                {
                    Encoding encoding = context.Response.ContentEncoding;

                    
                    
                    string html = encoding.GetString(buffer, offset, count);
//在这里可以用你熟悉的方法修改html
                    byte[] bytes = encoding.GetBytes(html);
                    output.Write(bytes, 0, bytes.Length);
                }
                else
                    output.Write(buffer, offset, count);
            }
        }
    }

然后把Response的Stream给换掉,偷梁换柱,哈哈……

CatchTextStream responseStream = new CatchTextStream(Response.Filter);
                    Response.Filter = responseStream;

为什么Response的Stream不能读呢?

这样就不行New StreamReader(Response.Filter);运行时报错,还请大家指点

posted @ 2013-08-01 17:05  幸运的程序员  阅读(1039)  评论(0编辑  收藏  举报