I was wondering if you have any advice on a problem I am seeing. I am creating an HttpModule where in the OnBeginRequest, I create a wrapper stream passing in the Request.Filter (I tried to pass in the Request.InputStream but when I run my application, I get an HttpException saying The request filter is not valid) into it and then set that wrapper stream as the filter doing something like Request.Filter = myWrapper. In my wrapper class I implement all the Stream methods, with the main one being of course the Read method where I was hoping to grab the bytes that are read and then write them out somewhere else. What is odd is I was expecting that when the InputStream was accessed (which I was doing in my test app in its Application_Begin_Request, it would be indirectly using my filter, but it does not. Is there anything else I need to enable in order for my wrapper class to be enabled as the Filter when InputStream is use on the Request?
Thanks in advance for any advice!
public class RequestLoggingFilter : IHttpModule
protected void OnBeginRequest(object sender, EventArgs ea) {
HttpApplication application = (HttpApplication)sender;
HttpRequestLog httpRequestLog = new HttpRequestLog();
application.Context.Items.Add("HttpRequestLog", httpRequestLog);
WrapperInputStream wrapperInputStream = new WrapperInputStream(application.Request.Filter);
httpRequestLog.WrapperInputStream = wrapperInputStream;
application.Request.Filter = wrapperInputStream;
}
.....
}
public class WrapperInputStream : Stream{
public WrapperInputStream(Stream inputStream) {
mInputStream = inputStream;
if (inputStream.Length > 0) {
mOutputStream = new MemoryStream((int)inputStream.Length);
}
else {
mOutputStream = new MemoryStream();
}
}
public override int Read(byte[] buffer, int offset, int count) {
int readBytes = mInputStream.Read(buffer, offset, count);
if (readBytes > 0) {
mOutputStream.Write(buffer, offset, readBytes);
mDataCaptureStarted = true;
if (readBytes == count) {
mDataCaptureComplete = true;
}
}
else {
mDataCaptureComplete = true;
}
return readBytes;
}
...
}
public class Global : System.Web.HttpApplication {
protected void Application_BeginRequest(object sender, EventArgs e) {
String mBody = "";
Stream stream = ((HttpApplication)sender).Request.InputStream;
int length = (int)stream.Length;
logger.Info(length);
try {
byte[] bytes = new byte[length];
stream.Read(bytes, 0, length);
foreach (byte b in bytes) {
mBody += (Char)b;
}
//StreamReader reader = new StreamReader(((HttpApplication)sender).Request.InputStream);
//mBody = reader.ReadToEnd();
//reader.Close();
}
catch (Exception ex) {
mBody = "Error decoding body: " + ex.Message;
}
logger.Info(mBody);
}
...
}