how to capture the HTTPResponseBody data in ASP.Net?

488 views Asked by At

I have written a HTTPModule after deriving from IHttpModule as follows.

public void Init(HttpApplication httpApplication)
{
    EventHandlerTaskAsyncHelper taskAsyncHelper = new EventHandlerTaskAsyncHelper(LogMessage);
    httpApplication.AddOnBeginRequestAsync(taskAsyncHelper.BeginEventHandler, taskAsyncHelper.EndEventHandler);
}

private async Task LogMessage(object sender, EventArgs e)
{
           var app = (HttpApplication)sender;
            var ctx = app.Context;
           string myURL = ((HttpApplication)sender).Context.Request.Url.ToString();

          StreamReader reader = new StreamReader(((HttpApplication)sender).Context.Request.InputStream);

            try
            {
                string body = reader.ReadToEnd();
            }
            finally
            {
                reader.BaseStream.Position = 0;
            }

            StreamReader ResponseStreamReader = new StreamReader(((HttpApplication)sender).Context.Response.OutputStream);

}

The StreamReader code is throwing error(the exact error message is: System.ArgumentException: Stream was not readable).

How can I read the ResponseBody of a HTTP request. I am using .Net 4.5. Thank you, John

2

There are 2 answers

0
John H On BEST ANSWER

The OutputStream represents the output as it is being written, so you may need to set the reader position to 0 before attempting to read from it.

0
J.Althaus On

You can not do it that way. The OutputStream is a write-only-stream.

Another approach is to use the Filter-property on the response object, see

http://www.drdobbs.com/windows/post-processing-the-output-of-aspnet-pag/212001499

I am using the following code:

public class LogModule : IHttpModule
{
    private string _filename;

    public void Dispose()
    {
    }

    public void Init(HttpApplication app)
    {
        _filename = "C:\\Temp\\iislog.log";
        app.PostRequestHandlerExecute += OnPostRequestHandlerExecute;
    }

    private void OnPostRequestHandlerExecute(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        if (app != null)
        {
            app.Response.Filter = new FilterStream(app.Response.Filter, _filename);
        }
    }
}

internal class FilterStream : MemoryStream
{
    private readonly Stream _outputStream;
    private readonly string _fileName;

    public FilterStream(Stream outputStream, string filename)
    {
        _outputStream = outputStream;
        _fileName = filename;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        File.AppendAllText(_fileName, Encoding.UTF8.GetString(buffer));
        _outputStream.Write(buffer, offset, count);
    }
}