你怎么测试你的Request.QueryString []变量? [英] How do you test your Request.QueryString[] variables?

查看:195
本文介绍了你怎么测试你的Request.QueryString []变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用的Request.QueryString [] 变量。

在我的的Page_Load 我经常做这样的事情:

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);

这一切似乎有点笨重和垃圾。你怎么处理你的的Request.QueryString [] S'

推荐答案

下面是一个扩展方法,让你写code是这样的:

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");

它利用 TypeDescriptor 来执行转换。根据您的需求,您可以添加一个重载需要一个默认值,而不是抛出一个异常的:

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);
}

这篇关于你怎么测试你的Request.QueryString []变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆