How do you test your Request.QueryString[] variabl

2019-01-07 02:45发布

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

In my Page_load I often do things like:

       int id = -1;

        if (Request.QueryString["id"] != null) {
            try
            {
                id = int.Parse(Request.QueryString["id"]);
            }
            catch
            {
                // deal with it
            }
        }

        DoSomethingSpectacularNow(id);

It all seems a bit clunky and rubbish. How do you deal with your Request.QueryString[]s?

11条回答
甜甜的少女心
2楼-- · 2019-01-07 03:00

Below is an extension method that will allow you to write code like this:

int id = request.QueryString.GetValue<int>("id");
DateTime date = request.QueryString.GetValue<DateTime>("date");

It makes use of TypeDescriptor to perform the conversion. Based on your needs, you could add an overload which takes a default value instead of throwing an exception:

public static T GetValue<T>(this NameValueCollection collection, string key)
{
    if(collection == null)
    {
        throw new ArgumentNullException("collection");
    }

    var value = collection[key];

    if(value == null)
    {
        throw new ArgumentOutOfRangeException("key");
    }

    var converter = TypeDescriptor.GetConverter(typeof(T));

    if(!converter.CanConvertFrom(typeof(string)))
    {
        throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));
    }

    return (T) converter.ConvertFrom(value);
}
查看更多
Lonely孤独者°
3楼-- · 2019-01-07 03:00

You can use the extension methods below as well and do like this

int? id = Request["id"].ToInt();
if(id.HasValue)
{

}

// Extension methods

public static int? ToInt(this string input) 
{
    int val;
    if (int.TryParse(input, out val))
        return val;
    return null;
}

public static DateTime? ToDate(this string input)
{
    DateTime val;
    if (DateTime.TryParse(input, out val))
        return val;
    return null;
}

public static decimal? ToDecimal(this string input)
{
    decimal val;
    if (decimal.TryParse(input, out val))
        return val;
    return null;
}
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-07 03:02

Try this dude...

List<string> keys = new List<string>(Request.QueryString.AllKeys);

Then you will be able to search the guy for a string real easy via...

keys.Contains("someKey")
查看更多
We Are One
5楼-- · 2019-01-07 03:02
if(!string.IsNullOrEmpty(Request.QueryString["id"]))
{
//querystring contains id
}
查看更多
Melony?
6楼-- · 2019-01-07 03:05

I do have functions for each (actually it's one small class, with lots of statics):

  • GetIntegerFromQuerystring(val)
  • GetIntegerFromPost(val)
  • ....

It returns -1 if fails (which is almost always OK for me, I have some other functions for negative numbers as well).

Dim X as Integer = GetIntegerFromQuerystring("id")
If x = -1 Then Exit Sub
查看更多
相关推荐>>
7楼-- · 2019-01-07 03:07

Use int.TryParse instead to get rid of the try-catch block:

if (!int.TryParse(Request.QueryString["id"], out id))
{
  // error case
}
查看更多
登录 后发表回答