Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test your Request.QueryString[] variables?

I frequently make use of Request.QueryString[] variables.

In my Page_load I often do things like:

       int id = -1;          if (Request.QueryString["id"] != null) {             try             {                 id = int.Parse(Request.QueryString["id"]);             }             catch             {                 // deal with it             }         }          DoSomethingSpectacularNow(id); 

It all seems a bit clunky and rubbish. How do you deal with your Request.QueryString[]s?

like image 310
Ian G Avatar asked Dec 08 '08 14:12

Ian G


People also ask

What is request QueryString ()?

The value of Request. QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request. QueryString(parameter).

How do you use a QueryString?

A Query String Collection is used to retrieve the variable values in the HTTP query string. If we want to transfer a large amount of data then we can't use the Request. QueryString. Query Strings are also generated by form submission or can be used by a user typing a query into the address bar of the browsers.

How do I check if a query string parameter exists?

Check if a query string parameter existsThe URLSearchParams.has() method returns true if a parameter with a specified name exists.

What is the use of request QueryString and Request form?

Form, the Web server parses the HTTP request body and returns the specified data. If your application requires unparsed data from the form, you can access it by calling Request. Form without any parameters. The QueryString collection retrieves the values of the variables in the HTTP query string.


1 Answers

Below is an extension method that will allow you to write code like this:

int id = request.QueryString.GetValue<int>("id"); DateTime date = request.QueryString.GetValue<DateTime>("date"); 

It makes use of TypeDescriptor to perform the conversion. Based on your needs, you could add an overload which takes a default value instead of throwing an exception:

public static T GetValue<T>(this NameValueCollection collection, string key) {     if(collection == null)     {         throw new ArgumentNullException("collection");     }      var value = collection[key];      if(value == null)     {         throw new ArgumentOutOfRangeException("key");     }      var converter = TypeDescriptor.GetConverter(typeof(T));      if(!converter.CanConvertFrom(typeof(string)))     {         throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));     }      return (T) converter.ConvertFrom(value); } 
like image 195
Bryan Watts Avatar answered Sep 19 '22 18:09

Bryan Watts