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

Page_load 我通常不喜欢的东西:

       int id = -1;

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

        DoSomethingSpectacularNow(id);

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

有帮助吗?

解决方案

下面是一个扩展方法,将允许你写这样的代码:

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

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

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

其他提示

使用int.TryParse而不是摆脱try-catch块的:

if (!int.TryParse(Request.QueryString["id"], out id))
{
  // error case
}

尝试这哥们儿...

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

然后你就可以搜索字符串真正轻松地通过...

的家伙
keys.Contains("someKey")

我使用一点辅助方法:

public static int QueryString(string paramName, int defaultValue)
{
    int value;
    if (!int.TryParse(Request.QueryString[paramName], out value))
        return defaultValue;
    return value;
}

这个方法允许我以下述方式读取来自查询字符串值:

int id = QueryString("id", 0);

好了一所件事用int.TryParse,而不是...

int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
    id = -1;
}

这假定“不存在”应该具有相同的结果,当然“不是一个整数”。

编辑:在其他情况下,当你还是要用请求参数字符串,我认为这绝对是一个好主意,以验证他们目前

可以使用下面以及扩展方法,做这样的

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

}

//扩展方法

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;
}
if(!string.IsNullOrEmpty(Request.QueryString["id"]))
{
//querystring contains id
}

EEEE这是一个业力风险...

我是干性单位可测试的抽象,因为,因为有太多的查询字符串变量在传统转化为继续。

从公用类,其构造下面的代码是需要的NameValueCollection输入(this.source)和字符串数组“钥匙”是因为继承应用程序是相当有机和已制定了几个不同的字符串是一个潜在的可能性输入键。不过我挺喜欢的可扩展性。该方法检查该集合的密钥和所需要的数据类型返回它。

private T GetValue<T>(string[] keys)
{
    return GetValue<T>(keys, default(T));
}

private T GetValue<T>(string[] keys, T vDefault)
{
    T x = vDefault;

    string v = null;

    for (int i = 0; i < keys.Length && String.IsNullOrEmpty(v); i++)
    {
        v = this.source[keys[i]];
    }

    if (!String.IsNullOrEmpty(v))
    {
        try
        {
            x = (typeof(T).IsSubclassOf(typeof(Enum))) ? (T)Enum.Parse(typeof(T), v) : (T)Convert.ChangeType(v, typeof(T));
        }
        catch(Exception e)
        {
            //do whatever you want here
        }
    }

    return x;
}

其实,我有一个使用泛型“包装”会议,这确实所有的“繁重的工作”为我的一个实用工具类,我也有一些几乎相同的查询字符串与工作价值。

这有助于消除代码欺骗为(通常大量)检查..

例如:

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

注意:

这显然使得使用静态的,有些人不喜欢,因为这会影响到测试代码的方式。你可以很容易地重构到该作品根据情况和您所需要的任何东西的接口..我只是想静力学例子是最轻的。

希望这有助于/给人深思。

我有功能每个(实际上它是一个小类,有大量的静态):

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

它返回-1如果失败(这几乎是始终是确定对我来说,我还有其他一些功能为负数,以及).

Dim X as Integer = GetIntegerFromQuerystring("id")
If x = -1 Then Exit Sub

我修改布莱恩瓦特的答案,这样,如果帕拉姆您的要价不存在,并已指定可空类型,将返回null:

public static T GetValue<T>(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);
    }

您现在可以做到这一点:

Request.QueryString.GetValue<int?>(paramName) ?? 10;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top