我经常使用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[]
?
答案 0 :(得分:52)
下面是一个扩展方法,允许您编写如下代码:
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);
}
答案 1 :(得分:34)
使用int.TryParse来取消try-catch块:
if (!int.TryParse(Request.QueryString["id"], out id))
{
// error case
}
答案 2 :(得分:19)
试试这个家伙...
List<string> keys = new List<string>(Request.QueryString.AllKeys);
然后你就可以通过...来搜索这个家伙的字符串了。
keys.Contains("someKey")
答案 3 :(得分:17)
我正在使用一个小帮手方法:
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);
答案 4 :(得分:10)
好吧,有一件事使用int.TryParse而不是......
int id;
if (!int.TryParse(Request.QueryString["id"], out id))
{
id = -1;
}
假设“不存在”应该与“非整数”结果相同。
编辑:在其他情况下,当你打算将请求参数用作字符串时,我认为验证它们是否存在肯定是一个好主意。
答案 5 :(得分:9)
你也可以使用下面的扩展方法,并按照这样做
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;
}
答案 6 :(得分:4)
if(!string.IsNullOrEmpty(Request.QueryString["id"]))
{
//querystring contains id
}
答案 7 :(得分:1)
我确实有每个函数(实际上它是一个小类,有很多静态函数):
GetIntegerFromQuerystring(val)
GetIntegerFromPost(val)
....
如果失败则返回-1(对我来说几乎总是好的,我还有其他一些负数的函数)。
Dim X as Integer = GetIntegerFromQuerystring("id")
If x = -1 Then Exit Sub
答案 8 :(得分:1)
Eeee这是一个业力风险......
我有一个DRY单元可测试的抽象,因为,因为在传统转换中有太多的查询字符串变量。
下面的代码来自一个实用程序类,其构造函数需要一个NameValueCollection输入(this.source),字符串数组“keys”是因为遗留应用程序非常有机,并且已经开发出了几个不同字符串成为潜在的可能性输入键。但是我有点像可扩展性。此方法检查密钥的集合,并以所需的数据类型返回。
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;
}
答案 9 :(得分:1)
我实际上有一个实用程序类,它使用Generics来“包装”会话,它为我完成所有“笨拙的工作”,我也有一些与QueryString值一样的几乎相同的东西。
这有助于删除(通常很多)支票的代码欺骗..
例如:
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");
}
注意:强>
这显然利用了静态,有些人不喜欢它,因为它可以影响测试代码。你可以轻松地重构为基于实例和你需要的任何接口工作的东西。我只是认为静态示例是最轻的。
希望这有助于/给予深思。
答案 10 :(得分:1)
我修改了Bryan Watts的答案,这样如果你的提问的参数不存在而且你指定了一个可空的类型,它将返回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;