我经常使用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[]的?
发布于 2008-12-08 15:11:01
下面是一个扩展方法,它允许您编写如下代码:
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);
}发布于 2008-12-08 14:42:01
改用int.TryParse来摆脱try-catch块:
if (!int.TryParse(Request.QueryString["id"], out id))
{
// error case
}发布于 2010-09-30 03:52:44
试试这家伙..。
List<string> keys = new List<string>(Request.QueryString.AllKeys);然后你就可以很容易地通过...
keys.Contains("someKey")https://stackoverflow.com/questions/349742
复制相似问题