Odd HttpRequest behaviour
I have a web service which runs with a HttpHandler class. In this class, I inspect the request stream for form / query string parameters. In some circumstances, it seemed as though these parameters weren't getting through. After a bit of digging around, I came across some behaviour I don't quite understand. See below:
// The request contains 'a=1&b=2&c=3' // TEST ONLY: Read the entire request string contents; using (StreamReader sr = new StreamReader(context.Request.InputStream)) { contents = sr.ReadToEnd(); } // Here 'contents' is usually correct - containing 'a=1&b=2&c=3'. Sometimes it is empty. string a = context.Request["a"]; // Here, a = null, regardless of whether the 'contents' variable above is correct
Can anyone explain to me why this might be hap开发者_如何转开发pening? I'm using a .NET WebClient and UploadDataAsync to perform the request on the client if that makes any difference.
If you need any more information, please let me know.
Why are you inspecting the request stream for query string parameters? There are a lot of built in types within .Net to deal with HTTP Requests. You can easily get a proper NameValueCollection from the querystring with the following code;
NameValueCollection queryStringValues =
HttpUtility.ParseQueryString(HttpContext.Current.Request.Query.ToLower());
string value = queryStringValues["my_key"];
In your code you have a StreamReader
read the stream and assign this to a string variable called contents
. However when you assign the value to string a
you access a variable called context
which I assume is really HttpContext.Current
. You then use the Request
object as a NameValueCollection
. When you access the Request
collection like that it looks for both POST and GET parameters checking both Request.Form
and Request.QueryString
.
Unless something further up the HTTP request pipeline is changing the request enroute you won't loose parameters. Use a proxy tool like Fiddler or Charles to inspect the request as it leaves the browser.
精彩评论