How do you check the variables Request.QueryString []?

I often use the variables Request.QueryString[] .

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); 

Everything seems a little awkward and trashy. How do you feel about your Request.QueryString[] s?

+49
c # coding-style isnumeric tryparse
Dec 08 '08 at 14:39
source share
11 answers

The following is an extension method that allows you to write code like this:

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

To perform the conversion, TypeDescriptor used. Based on your needs, you can add overload, which takes the default value and does not throw 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); } 
+51
Dec 08 '08 at 15:11
source share

Use int.TryParse instead to get rid of the try-catch block:

 if (!int.TryParse(Request.QueryString["id"], out id)) { // error case } 
+32
Dec 08 '08 at 14:42
source share

Try this dude ...

 List<string> keys = new List<string>(Request.QueryString.AllKeys); 

Then you can look for a guy for a string simple with ...

 keys.Contains("someKey") 
+19
Sep 29 '10 at 19:52
source share

I use a small helper method:

 public static int QueryString(string paramName, int defaultValue) { int value; if (!int.TryParse(Request.QueryString[paramName], out value)) return defaultValue; return value; } 

This method allows me to read values ​​from the query string as follows:

 int id = QueryString("id", 0); 
+17
Dec 08 '08 at 14:50
source share

Well, for one thing, use int.TryParse instead ...

 int id; if (!int.TryParse(Request.QueryString["id"], out id)) { id = -1; } 

This suggests that no should have the same result as non-integer.

EDIT: In other cases, when you are going to use query parameters as strings anyway, I think it is definitely a good idea to confirm that they are present.

+10
Dec 08 '08 at 14:43
source share

You can also use extension methods and do it

 int? id = Request["id"].ToInt(); if(id.HasValue) { } 

// Extension Methods

 public static int? ToInt(this string input) { int val; if (int.TryParse(input, out val)) return val; return null; } public static DateTime? ToDate(this string input) { DateTime val; if (DateTime.TryParse(input, out val)) return val; return null; } public static decimal? ToDecimal(this string input) { decimal val; if (decimal.TryParse(input, out val)) return val; return null; } 
+9
Dec 08 '08 at 14:58
source share
 if(!string.IsNullOrEmpty(Request.QueryString["id"])) { //querystring contains id } 
+4
Dec 08 '08 at 14:44
source share

I have functions for each (actually this is one small class with a lot of statics):

  • GetIntegerFromQuerystring(val)
  • GetIntegerFromPost(val)
  • ....

It returns -1 if it crashes (which is almost always normal for me, I have other functions for negative numbers).

 Dim X as Integer = GetIntegerFromQuerystring("id") If x = -1 Then Exit Sub 
+1
Dec 08 '08 at 14:49
source share

Eeee is the risk of karma ...

I have a DRY absorbed unit of measure, because, since there are too many query variables to continue the inheritance conversion,

Below is the utility code, the constructor of which requires the input of NameValueCollection (this.source) and the "keys" of the string array, because the legacy application was quite organic and developed the ability for several different strings to be a potential input key. However, I kind of like extensibility. This method checks the collection for the key and returns it in the required data type.

 private T GetValue<T>(string[] keys) { return GetValue<T>(keys, default(T)); } private T GetValue<T>(string[] keys, T vDefault) { T x = vDefault; string v = null; for (int i = 0; i < keys.Length && String.IsNullOrEmpty(v); i++) { v = this.source[keys[i]]; } if (!String.IsNullOrEmpty(v)) { try { x = (typeof(T).IsSubclassOf(typeof(Enum))) ? (T)Enum.Parse(typeof(T), v) : (T)Convert.ChangeType(v, typeof(T)); } catch(Exception e) { //do whatever you want here } } return x; } 
+1
Dec 08 '08 at 14:54
source share

Actually, I have a utility class that uses Generics for the “wrap” session, which does all the “grunt work” for me, I also have something almost identical for working with QueryString values.

This helps to remove duplicate code for (often numerous) checks.

For example:

 public class QueryString { static NameValueCollection QS { get { if (HttpContext.Current == null) throw new ApplicationException("No HttpContext!"); return HttpContext.Current.Request.QueryString; } } public static int Int(string key) { int i; if (!int.TryParse(QS[key], out i)) i = -1; // Obviously Change as you see fit. return i; } // ... Other types omitted. } // And to Use.. void Test() { int i = QueryString.Int("test"); } 

Note:

This obviously uses statics, which some people dislike because of how it can affect the test code. You can easily reorganize what works on the basis of instances and any interfaces necessary for you. I just think the static example is the easiest.

Hope this helps / gives food for thought.

+1
Dec 08 '08 at 14:57
source share

I changed Brian Watts answer so that if the parameter that your request does not exist and you specified a null type, it will return null:

 public static T GetValue<T>(this NameValueCollection collection, string key) { if (collection == null) { return default(T); } var value = collection[key]; if (value == null) { return default(T); } var type = typeof(T); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = Nullable.GetUnderlyingType(type); } var converter = TypeDescriptor.GetConverter(type); if (!converter.CanConvertTo(value.GetType())) { return default(T); } return (T)converter.ConvertTo(value, type); } 

Now you can do this:

 Request.QueryString.GetValue<int?>(paramName) ?? 10; 
+1
Oct 19 '09 at 19:00
source share



All Articles