怎样修改Response中的内容

本文介绍了一种在ASP.NET中重写Response Stream的方法,通过创建一个名为CatchTextStream的自定义类,该类继承自Stream。这个自定义类允许在发送到客户端前拦截和修改HTML内容,特别适用于动态网页应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

重写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);运行时报错,还请大家指点

转载于:https://www.cnblogs.com/LLLLoveLLLLife/p/3230472.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值