【发布时间】:2009-02-22 12:45:30
【问题描述】:
如果您一直在寻找一种简洁明了的方式来解析您的查询字符串值,我想出了这个:
/// <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);
}
我一直都想拥有这样的东西,最后做对了……至少我是这么认为的……
代码应该是不言自明的......
感谢任何改进它的 cmets 或建议。
【问题讨论】:
-
也许您在代码堆栈中较早处理它,但请记住,查询字符串中的键可以有多个值,即 x=1,2,3
-
@jro 我会认为多值大小写是无效的,因为就查询字符串而言,它只有一个值,一个字符串“1,2,3”,解析它就像其他任何东西一样不正确。
标签: c# asp.net query-string