Query strings are something we deal with constantly. I’ve come up with a helper that uses .NET Generics to handle a lot of common cases that we usually write unnecessary code for.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
public class QS { public static T Value<t>(string parameterName) where T : IConvertible { if (HttpContext.Current == null) throw new InvalidOperationException("Cannot call QS<t> when HttpContext.Current is null"); if (string.IsNullOrEmpty(HttpContext.Current.Request[parameterName])) throw new InvalidOperationException( string.Format("Expected query string parameter named '{0}' to exist", parameterName)); return Value<t>(parameterName, default(T)); } public static T Value<t>(string parameterName, T defaultValue) where T : IConvertible { if (HttpContext.Current == null) throw new InvalidOperationException("Cannot call QS<t> when HttpContext.Current is null"); HttpRequest request = HttpContext.Current.Request; string input; if (request.QueryString[parameterName] != null && !string.IsNullOrEmpty(request.QueryString[parameterName])) input = request.QueryString[parameterName]; else return defaultValue; T value; try { value = (T)Convert.ChangeType(input, typeof(T)); } catch (Exception ex) { throw new InvalidOperationException( string.Format("Unable to convert query string parameter named '{0}' with value of '{1}' to type {2}", parameterName, input, typeof(T).FullName), ex); } return value; } } |
Usage:
1 2 3 4 5 |
// Required. Will throw exceptions if the query string value is null or empty string int personID = QS.Value("personID"); string keywords = QS.Value("keywords"); // Optional. Use default value if query string value is null or empty int startIndex = QS.Value("startIndex", 0); |