开发者

Query String to Object with strongly typed properties

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?


I am not sure if you are using it or not, but ASP.NET MVC will handle this for you. You can define all of your parameters in the action's signature, and any you don' t receive will be null.


Another solution would perhaps be a custom enum class(with one value for each parameter) with custom ToString() method. You could then reverse lookup the string to get the enum value, use that in your switch case. In case of invalid parameters, an exception can be thrown during reverse lookup.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜