tags:

views:

279

answers:

1

Here's an easy one for you:

I'm currently logging request duration via an HttpModule and I'd like to find out the number of bytes each page is as well.

HttpContext.Current.Response.OutputStream.Length throws a NotSupportedException.

What's an easy way to do this?

+2  A: 

I have an HttpModule that implements a stream rewriter. It derives from the Stream class. In my HttpModule I have the following code:

void app_PreRequestHandlerExecute(object sender, EventArgs e)
{
    HttpResponse response = HttpContext.Current.Response;
    response.Filter = new MyRewriterStream(response.Filter);
}

In the stream class I have the following code that overrides the default Write method:

public override void Write(byte[] buffer, int offset, int count)
{
     string outStr;
     outStr = UTF8Encoding.UTF8.GetString(buffer, offset, count);
     //Do useful stuff and write back to the stream
}

You can just take the length of the string at the second point

Jason Z
Do yo mean:response.Filter = new MyRewriterStream(response.OutputStream) ??
Ben Scheirman
nevermind, you were right... it just looked like a typo.That did it!
Ben Scheirman
Be careful about converting the byte[] buffer to a string if the request is for a binary file.
David