Query String to Object with strongly typed properties
Posted
by Kamar
on Stack Overflow
See other posts from Stack Overflow
or by Kamar
Published on 2010-06-07T18:30:12Z
Indexed on
2010/06/07
18:32 UTC
Read the original article
Hit count: 251
c#
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?
© Stack Overflow or respective owner