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

前端 未结 11 2174
梦如初夏
梦如初夏 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:44

    I modified Bryan Watts' answer so that if the param your asking does not exist and you have specified a nullable type it will return null :

    public static T GetValue(this NameValueCollection collection, string key)
        {
            if (collection == null)
            {
                return default(T);
            }
    
            var value = collection[key];
    
            if (value == null)
            {
               return default(T);
            }
    
            var type = typeof(T);
    
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                type = Nullable.GetUnderlyingType(type);
            }
    
            var converter = TypeDescriptor.GetConverter(type);
    
            if (!converter.CanConvertTo(value.GetType()))
            {
                return default(T);
            }
    
            return (T)converter.ConvertTo(value, type);
        }
    

    You can now do this :

    Request.QueryString.GetValue(paramName) ?? 10;
    

提交回复
热议问题