Query String to Object with strongly typed properties
- by Kamar
Let’s say we track 20 query string parameters in our site. Each request which comes will have only a subset of those 20 parameters. But we definitely look for all/most of the parameters which comes in each request.
We do not want to loop through the collection each time we are looking for a particular parameter initially or somewhere down the pipeline in the code. So we loop once through the query string collection, convert string values to their respective types (enums, int, string etc.), populate to QueryString object which is added to the context.
After that wherever its needed we will have a strongly typed properties in the QueryString object which is easy to use and we maintain a standard.
public class QueryString
{
public int Key1{ get; private set; }
public SomeType Key2{ get; private set; }
private QueryString() { }
public static QueryString GetQueryString()
{
QueryString l_QS = new QueryString();
foreach (string l_Key in HttpContext.Current.Request.QueryString.AllKeys)
{
switch (l_Key)
{
case "key1":
l_QS.Key1= DoSomething(l_Key, HttpContext.Current.Request.QueryString[l_Key]);
break;
case "key2":
l_QS.Key2 = DoAnotherThing(l_Key, HttpContext.Current.Request.QueryString[l_Key]);
break;
}
}
return l_QS;
}
}
Any other solution to achieve this?