Can any one tell me is there any difference between:
Request.QueryString["id"]
and Request["id"]
If yes which is better to use?
Can any one tell me is there any difference between:
Request.QueryString["id"]
and Request["id"]
If yes which is better to use?
Request["id"]
gets a value from the QueryString
, Form
, Cookies
, or ServerVariables
collections. The order in which they are searched is not specified in the documentation but when you take a look at the source code you'll see that it is the order in which they are mentioned.
So if you know where your variable resides, which you usually do, it's better to use the more specific option.
Request.QueryString["id"]
will return the value of an item in the query string that has a key of id
, whereas Request["id"]
will return an item from one of Request.QueryString, Request.Form, Request.Cookies, or Request.ServerVariables.
It's worth mentioning that the documentation for Request.Item
(which is what you're actually accessing when you call Request["id"]
) does not specify the order in which the collections will be searched, so you could theoretically receive a different result depending on which version of asp.net you're running on.
If you know that the value you want is in your query string, it's always better to use Request.QueryString["id"]
to access it, rather than Request["id"]
.
According to the documentation the HttpRequest
indexer
The QueryString, Form, Cookies, or ServerVariables collection member specified in the key parameter.
I'd prefer using Request.QueryString["id"]
since it's more explicit where the value is coming from.
Request.QueryString["id"] looks into the collection passed per QueryString. Request.Item["id"] looks into all Collections(QueryString, Form, Cookies, or ServerVariables). Therefore the QueryString Property should be preferred when possible because it is smaller.
the Request collection is a superset of QueryString, along with some more data related to the current request.
so as for "better" - I'd advise you'd be precise and explicit (i.e. use QueryString) to avoid the surprise factor, when you get unexpected results just to realise that you used a key for which a given request did not supply a query-string value, but it exists on some other collection.
According to Reflector.Net, Request["id"] is defined as:
public string this[string key]
{
get
{
string str = this.QueryString[key];
if (str != null)
{
return str;
}
str = this.Form[key];
if (str != null)
{
return str;
}
HttpCookie cookie = this.Cookies[key];
if (cookie != null)
{
return cookie.Value;
}
str = this.ServerVariables[key];
if (str != null)
{
return str;
}
return null;
}
}