33

我正在尝试使用 IHttpModule 记录 http 请求的内容,如下所示:

public class LoggingModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += ContextBeginRequest;
    }

    private void ContextBeginRequest(object sender, EventArgs e)
    {
        var request = ((HttpApplication)sender).Request;
        string content;

        using (var reader = new StreamReader(request.InputStream))
        {
            content = reader.ReadToEnd();
        }

        LogRequest(content)
    }
}

问题是在将输入流读到最后之后,InputStream 似乎要么消失了,要么更有可能是光标在流的末尾。

我已经尝试过request.InputStream.Position = 0;request.InputStream.Seek(0, SeekOrigin.Begin);但都没有工作。

4

6 回答 6

46

我已经解决了这个问题:我认为在 StreamReader 上调用 dispose 也必须杀死 InputStream。

我没有使用 StreamReader,而是执行了以下操作:

        var bytes = new byte[request.InputStream.Length];
        request.InputStream.Read(bytes, 0, bytes.Length);
        request.InputStream.Position = 0;
        string content = Encoding.ASCII.GetString(bytes);

所以完整的代码:

public class LoggingModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += ContextBeginRequest;
    }

    private void ContextBeginRequest(object sender, EventArgs e)
    {
        var request = ((HttpApplication)sender).Request;

        var bytes = new byte[request.InputStream.Length];
        request.InputStream.Read(bytes, 0, bytes.Length);
        request.InputStream.Position = 0;
        string content = Encoding.ASCII.GetString(bytes);

        LogRequest(content)
    }
}
于 2009-11-05T07:25:48.343 回答
23

是的,StreamReader 将关闭提供的流。

如果您使用的是 >v4.5,请使用保持流打开的 StreamReader 构造函数。

using (var reader = new StreamReader(request.InputStream, Encoding.UTF8, true, 1024, true))
{
    content = reader.ReadToEnd();
}
于 2013-11-29T01:50:46.927 回答
3

我不得不对“cbp”提供的答案做一个小的调整。使用他的代码时,我得到了零。我将位置设置为读取上方的 0,现在它可以工作了。

 var bytes = new byte[Request.InputStream.Length];
 Request.InputStream.Position = 0;
 Request.InputStream.Read(bytes, 0, bytes.Length);
 string content = Encoding.ASCII.GetString(bytes);
于 2016-03-10T17:39:08.057 回答
2

这个答案没有用。它返回一个包含空值的数组。

        var bytes = new byte[request.InputStream.Length];
        request.InputStream.Read(bytes, 0, bytes.Length);
        request.InputStream.Position = 0;
        字符串内容 = Encoding.ASCII.GetString(bytes);

因为输入流消耗了。

于 2010-01-26T15:28:27.960 回答
1

您需要使用请求过滤器。编写一个派生自Stream的类并将其注册为过滤器。

于 2009-11-05T07:20:33.440 回答
-1

有时,RequestFilter不要运行到方法 Read。似乎 W3WP 不httprequest以正常方式阅读内容。

如果部署WEbservice到服务器。然后使用 IHttpModule 捕获它。添加RequestFilter.

但是Read()RequestFilter 的方法不运行:P

于 2012-06-27T07:42:42.500 回答