Sunday, September 5, 2010

How to make use of Filter property of Response object

Response object has a property called Filter. Not surprisingly, you can use it to filter the response data and manipulate it. First, you need to define a class that derives from Stream class. You then need to implement the required methods and properties. In this case, you will need Read, Write and Flush methods to be implemented. If you use ‘Implement abstract class’ feature, all the abstract properties and methods will be placed in the code with a throw statement. You will need to remove the default throw statement from Flush method. Otherwise you will get an error message at run time. Here is a sample class:

public class ResponseFilter: Stream
{
      Stream baseStream;
      public ResponseFilter(Stream responseStream)

      {
            if (responseStream == null)
            {
                  throw new ArgumentNullException("ResponseStream");
            }
            baseStream = responseStream;
      }
      public override void Write(byte[] buffer, int offset, int count)
      {
            string text = Encoding.UTF8.GetString(buffer, offset, count);
            text = text.Replace("old_text", "new_text");
            buffer = Encoding.UTF8.GetBytes(text);
            baseStream.Write(buffer, 0, buffer.Length);
      }
      public override int Read(byte[] buffer, int offset, int count)
      {
            return baseStream.Read(buffer, offset, count);
      }
}

In the handler method of the Page’s Load event, Filter property needs to be set to an instance of the newly created class by passing in the Filter property to the constructor:

protected void Page_Load(object sender, EventArgs e)
{
      Response.Filter = new ResponseFilter(Response.Filter);
}

In this example, all occurances of the string "old_text" will be replaced with "new_text". It's not a very sophisticated example, but it shows how you can filter the response and modify the stream.

No comments:

Post a Comment