Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How better check Request.QueryString string parameter for null?

I need explanations.. I using C#.NET to web applications, I always write:

 string val = Request.QueryString["foo"];

and then

if(!string.IsNullOrEmpty(val)) 

What's the difference:

string val = Request.QueryString["foo"];

I was advised to do:

string val = Request.QueryString["foo"] as string;
if(!string.IsNullOrEmpty(val)) 

What's the difference?

like image 421
The Mask Avatar asked Nov 13 '11 21:11

The Mask


People also ask

Are Querystring parameters case-sensitive?

The request query parameter names are case-sensitive.

Does the order of query params matter?

The order of parameters matters in query strings. In the following example, the query strings are identical except that the parameters are in a different order.

How do you check if a query string is null or not?

Request. QueryString. Count != 0 will simply tell you if there are no parameters at all.

How do you validate a Querystring?

Query string values can be checked using regular expressions. You can select regular expressions from the global White list or enter them manually. For example, if you know that a query string must have a value of ABCD , a regular expression of ^ABCD$ is an exact match test.


1 Answers

The first is better:

string val = Request.QueryString["foo"];

The second version returns null if the result of the call is not a string, but you know it always will be a string because the QueryString member has type NameValueCollection. The indexer is defined to return a string:

public class NameValueCollection : NameObjectCollectionBase
{
    // ...
    public string this[string name] { get; set; }
    // ...
}
like image 177
Mark Byers Avatar answered Oct 03 '22 18:10

Mark Byers