0

从IHttpModule派生后,我编写了一个 HTTPModule ,如下所示。

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);

}

StreamReader 代码抛出错误(确切的错误消息是:System.ArgumentException: Stream was not readable)。

如何读取 HTTP 请求的 ResponseBody。我正在使用.Net 4.5。谢谢你,约翰

4

2 回答 2

0

OutputStream 表示正在写入的输出,因此您可能需要在尝试读取之前将读取器位置设置为 0。

于 2014-11-17T21:54:05.710 回答
0

你不能那样做。OutputStream 是只写流。

另一种方法是在响应对象上使用 Filter-property,请参阅

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

我正在使用以下代码:

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);
    }
}
于 2018-04-13T10:26:49.670 回答