2009-11-05 1 views
23

のInputStreamの位置をリセット:HttpModuleを持つ要求InputStreamをログに記録する方法、そのようにのようなの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);を試しましたが、いずれも動作しません。

答えて

31

私は問題を解決しました。私は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) 
    } 
} 
+6

エンコードには注意してください。Encoding.UTF8.GetString(bytes); – SimonF

+0

偉大な答え! +1 –

1

request filterを使用する必要があります。 Streamから派生したクラスを作成し、フィルタとして登録します。

1

この答えは動作しませんでした。ヌル値を含む配列を返します。

入力ストリームが消費されたためです。

-1

いつか、RequestFilterメソッドの読み取りに実行されません。それはW3WPのように通常の方法でhttprequestの内容を読み取っていないようです。

WEbserviceをサーバーにデプロイする場合。その後、IHttpModuleを使用してキャッチします。 RequestFilterを追加します。

しかしRequestFilterの方法Read()は実行されません:P

13

はいStreamReaderをは、供給されたストリームを閉じます。

> v4.5の場合は、ストリームを開いたままにしておくStreamReaderコンストラクタを使用します。

using (var reader = new StreamReader(request.InputStream, Encoding.UTF8, true, 1024, true)) 
{ 
    content = reader.ReadToEnd(); 
} 
1

"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); 
関連する問題