I develop an asmx web service (i.e. ASP.NET 2.0).
There's a piece of code that may read the contents of the HTTP request (via HttpContext.Current.Request.InputStream
) while processing it. I realise that InputStream may only be read once for a request, and I make sure I never try to read it more than once.
The problem seems to be that if InputStream happens to be read during the early stages of the application's lifecycle (e.g. after pskill w3wp
, during Application_Start), the HTTP request fails with a HTTP 400 - Bad Req开发者_C百科uest error, with no explanation given, no exception thrown and no entry in the httperr log. If it is read later (e.g. within the web method itself), requests run fine whether InputStream is read or not. Application_Start runs fine if InputStream isn't read.
Is this some sort of ASP.NET bug? IIS bug? Or am I doing something wrong by daring to read InputStream? And if so, is there another way to get a look at the "raw" contents of the request without disturbing the inner workings of IIS/ASP.NET?
In short, adding this code within Application_Start is enough to reproduce this error:
using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))
reader.ReadToEnd();
Couldn't find a way to read request contents during Application_Start without disturbing inner workings of ASP.NET/IIS. Instead, ended up making sure this doesn't happen until Application_Start
is over (and also doesn't happen from the moment Application_End
starts, which also turned out to be problematic and created access violations).
You have to no use the using bloc because this has as effect to close the reader and by consequence to close the inputstream of httprequest
I would suggest not attempting to read the Request.InputStream
during Application_Start
- it's used for initialising the application. Accessing the Request object from within Application_Start results in an exception "Request is not available in this context."
The fact that you are wanting to read the input stream suggests you should be using Application_BeginRequest
instead - this has access to request and response.
In Summary:
Application_Start
Fires once when the application starts. While usually triggered by the first request, it occurs before the first request is set up. Don't do request specific code in here as it doesn't have access to Request and Response.Application_BeginRequest
Fires for every request before any page handlers are invoked - you can read the input, write to response, end the request, etc...
See these SO articles for more info:
- Request is not available in this context
- Replacement for HttpContext.Current.Request.ServerVariables["SERVER_NAME"] in Integrated Mode
- When does HttpRequest get created?
精彩评论