Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replace string in Response 1

Status
Not open for further replies.

MrGandalf

Programmer
Jul 19, 2005
35
NL
Hi,

Can anyone tell me how I can replace a string in the Response? And in which event to do this.

I have a 3party tool that injects some javascript function into the page. I want to filter this function.

Thanks in advance.
 
That's not what I mean. I want to replace a string that is already in the Response object.
 
You'd want to make an HttpModule and hook into the PreSendRequestContent event (or some other event).


This will let you intercept the request for manipulation before it's sent to the client. Just be sure that it's added after the third-party utility so it processes the request after the third-party tool executes.
 
Ok, let us asume I have intercept the Request. And there is a string: "I'm a string" in that Request. I want to replace that string "I'm NOT a string anymore".

What is the syntax to do this? Thus Request. what?
 
Hi,

I do not know how to do this or even if it is possible! Although you could use a label (asp control). Then you have to do: label1.text="I'm NOT a string anymore"


Hope i helped
 
Okay, so part of the original suggestion was flawed: in the PreSendRequestContent event, the response stream is actually write-only so you'd need a slightly different strategy.

The trick still involves an HttpModule, but you'd actually hook the Init event and plug in a different response filter object:

Code:
// ---------------------------------------------
public void Init (HttpApplication app)
{
 app.ReleaseRequestState += new EventHandler(InstallResponseFilter);
}

// ---------------------------------------------
private void InstallResponseFilter(object sender, EventArgs e) 
{
 HttpResponse response = HttpContext.Current.Response;

 if(response.ContentType == "text/html")
       response.Filter = new PageFilter (response.Filter);
}

The filter itself would store up the buffered response output until it's complete and ready to send, then before sending, you'd run a string replace function. Here's the code for the filter:

Code:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;

namespace AspNetResources.Web
{
/// <summary>
/// PageFilter does all the dirty work of tinkering the 
/// outgoing HTML stream. This is a good place to
/// enforce some compilancy with web standards.
/// </summary>
public class PageFilter : Stream
{
    Stream          responseStream;
    long            position;
    StringBuilder   responseHtml;

public PageFilter (Stream inputStream)
{
    responseStream = inputStream;
    responseHtml = new StringBuilder ();
}

#region Filter overrides
public override bool CanRead
{
    get { return true;}
}

public override bool CanSeek
{
    get { return true; }
}

public override bool CanWrite
{
    get { return true; }
}

public override void Close()
{
    responseStream.Close ();
}

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

public override long Length
{
    get { return 0; }
}

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

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

public override void SetLength(long length)
{
    responseStream.SetLength (length);
}

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

#region Dirty work
public override void Write(byte[] buffer, int offset, int count)
{
    string strBuffer = System.Text.UTF8Encoding.UTF8.«
                              GetString (buffer, offset, count);

    // ---------------------------------
    // Wait for the closing </html> tag
    // ---------------------------------
    Regex eof = new Regex ("</html>", RegexOptions.IgnoreCase);

    if (!eof.IsMatch (strBuffer))
    {
        responseHtml.Append (strBuffer);
    }
    else
    {
        responseHtml.Append (strBuffer);
        string  finalHtml = responseHtml.ToString ();

        [b]
        //here's where you'd manipulate the response.
        finalHtml = finalHtml.Replace( "blah", "whatever" ); [/b]

        byte[] data = System.Text.UTF8Encoding.UTF8.«
                              GetBytes (finalHtml);
        
        responseStream.Write (data, 0, data.Length);            
    }
}
#endregion

This goes into greater detail:
 
Thanks Boulderbon,

I will test it and let you know. It seems doable.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top