14 02 2013
ASP.NET Modules – reading InputStream with StreamReader
If, like me, if you’ve gotten into habit of wrapping most things that implement IDisposable in a ‘using’ statement, then you’ll be wondering why the hell you can’t read from the Requests’s InputStream property using a StreamReader without your request pipeline breaking.
Turns out, that you mustn’t dispose of the StreamReader immediately, as when you do this it will implicitly dispose of your InputStream also.
So, declare your StreamReader as a private member of your Module class, and only explicitly Dispose of it within the pre-canned Dispose method in the Module class.
Like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public class LoggingModule : IHttpModule { private StreamReader reader; // Declare the StreamReader here public void Dispose() { if (this.reader != null) // Dispose of it here this.reader.Dispose(); } public void Init(HttpApplication context) { context.LogRequest += new EventHandler(context_LogRequest); } void context_LogRequest(object sender, EventArgs e) { // DO NOT DISPOSE OF IT HERE! // It'll can your InputStream object if you do this.reader = new StreamReader(HttpContext.Current.Request.InputStream); string s = reader.ReadToEnd(); //Do some funky stuff with the text content of the input stream } } |
Goes without saying, remember to use BinaryReader if you’re not reading plain text in the input stream (in this case, I’m getting the payload of a POST request).
Unable to resolve NTLM or Windows users in People Picker in Central Admin SharePoint 2010 Server Search Only Crawling Top Level Site