C#ASP.NET QueryString解析器

And*_*llo 7 c# asp.net query-string

如果你一直在寻找一种很好的方法来解析你的查询字符串值,我想出了这个:

    /// <summary>
    /// Parses the query string and returns a valid value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key">The query string key.</param>
    /// <param name="value">The value.</param>
    protected internal T ParseQueryStringValue<T>(string key, string value)
    {
        if (!string.IsNullOrEmpty(value))
        {
            //TODO: Map other common QueryString parameters type ...
            if (typeof(T) == typeof(string))
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            if (typeof(T) == typeof(int))
            {
                int tempValue;
                if (!int.TryParse(value, out tempValue))
                {
                    throw new ApplicationException(string.Format("Invalid QueryString parameter {0}. The value " +
                                                              "'{1}' is not a valid {2} type.", key, value, "int"));
                }
                return (T)Convert.ChangeType(tempValue, typeof(T));
            }
            if (typeof(T) == typeof(DateTime))
            {
                DateTime tempValue;
                if (!DateTime.TryParse(value, out tempValue))
                {
                    throw new ApplicationException(string.Format("Invalid QueryString parameter {0}. The value " +
                                                         "'{1}' is not a valid {2} type.", key, value, "DateTime"));
                }
                return (T)Convert.ChangeType(tempValue, typeof(T));
            }
        }
        return default(T);
    }
Run Code Online (Sandbox Code Playgroud)

我一直想拥有这样的东西,最后做对了......至少我是这么认为的......

代码应该是自我解释的......

任何评论或建议,以使其更好,表示赞赏.

Sim*_*ver 34

一种简单的解析方法(如果你不想进行类型转换)是

 HttpUtility.ParseQueryString(queryString);
Run Code Online (Sandbox Code Playgroud)

您可以使用URL从URL中提取查询字符串

 new Uri(url).Query
Run Code Online (Sandbox Code Playgroud)

  • 仅当url是完整网址时才有效.如果您有相对URL,则不支持Uri的Query成员. (4认同)

Jon*_*eet 5

鉴于您只处理三种不同的类型,我建议使用三种不同的方法 - 当它们适用于类型约束所允许的每个类型参数时,泛型方法最佳.

另外,我强烈建议你intDateTime你指定要使用的文化 - 它不应该真正依赖于服务器所处的文化.(如果你有代码来猜测用户的文化,你可以使用它相反.)最后,我还建议支持一组明确指定的DateTime格式,而不是TryParse默认支持的任何格式.(我几乎总是使用ParseExact/ TryParseExact而不是Parse/ TryParse.)

请注意,字符串版本实际上并不需要执行任何操作,因为它value已经是一个字符串(尽管您当前的代码将"转换为" null,这可能是您想要的,也可能不是您想要的).