How do you test your Request.QueryString[] variables?

前端 未结 11 2143
梦如初夏
梦如初夏 2020-11-29 16:05

I frequently make use of Request.QueryString[] variables.

In my Page_load I often do things like:

       int id = -1;

             


        
11条回答
  •  一整个雨季
    2020-11-29 16:39

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

    This helps remove the code dupe for the (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 makes use of statics, which some people don't like because of the way it can impact test code.. You can easily refactor into something that works based on instances and any interfaces you require.. I just think the statics example is the lightest.

    Hope this helps/gives food for thought.

提交回复
热议问题