Request["key"]
vs Request.Params["key"]
vs Request.QueryString["key"]
Which method do you seasoned programmers use? and why?
Request["key"]
vs Request.Params["key"]
vs Request.QueryString["key"]
Which method do you seasoned programmers use? and why?
I prefer to use
Request.QueryString["key"]
because it helps the code-reader know exactly where you are getting the data from. I tend not to useRequest.Params["key"]
because it could refer to a cookie, query string and a few other things; so the user has to think a little. The less time someone needs to figure out what you are thinking, the easier it is to maintain the code.I always explicitly specify the collection. If for some reason you want to allow overrides, code the "get" for each one and write some clear code that shows your hierarchy for choosing one over the other. IMO, I dislike getting a value from multiple sources without a clear business reason for so doing.
I recommend
Request.QueryString["key"]
. There isn't a lot of difference toRequest["Key"]
for a query string but there is a big(er) difference if you are trying to get the value fromServerVariables
.Request["Key"]
looks for a value inQueryString
if null, it looks atForm
, thenCookie
and finallyServerVariables
.Using
Params
is the most costly. The first request to params creates a newNameValueCollection
and adds each of theQueryString
,Form
,Cookie
andServerVariables
to this collection. For the second request on it is more performant thanRequest["Key"]
.Having said that the performance difference for a couple of keys is fairly negligable. The key here is code should show intent and using
Request.QueryString
makes it clear what your intent is.As a kindly notice, If you set requestValidationMode="4.5" under web.config, both Request.QueryString[“key”] and Request[“key”] will use "lazy loading" behavior as design.
However, somehow Request.Params[“key”] will still trigger validation as the behavior of 4.0 .
This odd behavior really confuses me for a long time.
HttpRequest.Params
orRequest.Params
gets just about everything (querystring, form, cookie and session variables) from the httprequest, whereasRequest.Querystring
only will pull the querystring... all depends on what you are doing at the time.