我从 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无法读取)。
如何读取HTTP请求的ResponseBody。 我正在使用.Net 4.5。 谢谢, 约翰
答案 0 :(得分:0)
OutputStream表示正在写入的输出,因此您可能需要在尝试读取之前将读取器位置设置为0.
答案 1 :(得分: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);
}
}