How to log request inputstream with HttpModule, then reset InputStream position

后端 未结 6 1434
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 01:51

I am trying to log the contents of an http request, using an IHttpModule like so:

public class LoggingModule : IHttpModule
{
    public void Init(HttpApplica         


        
6条回答
  •  被撕碎了的回忆
    2020-12-09 02:33

    I've worked out the problem: I think that calling dispose on the StreamReader must be killing the InputStream too.

    Instead of using the StreamReader I did the following:

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

    So the complete code:

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

提交回复
热议问题