检查Request.QueryString中是否存在未分配的变量

在ASP.NET页面的上下文中,我可以使用Request.QueryString来获取URI的查询字符串部分中的键/值对的集合。

例如,如果我使用http://local/Default.aspx?test=value加载我的页面,那么我可以调用以下代码:

 //http://local/Default.aspx?test=value protected void Page_Load(object sender, EventArgs e) { string value = Request.QueryString["test"]; // == "value" } 

理想情况下,我想要检查是否存在测试 ,所以我可以使用http://local/Default.aspx?test调用该页面并获取一个布尔值,告诉我测试是否存在于查询字符串中。 像这样的东西:

 //http://local/Default.aspx?test protected void Page_Load(object sender, EventArgs e) { bool testExists = Request.QueryString.HasKey("test"); // == True } 

理想情况下,我想要的是一个布尔值,告诉我测试变量是否存在于字符串中。

我想我可以使用正则表达式检查字符串,但我很好奇是否有人有更优雅的解决方案。

我尝试过以下方法:

 //http://local/Default.aspx?test Request.QueryString.AllKeys.Contains("test"); // == False (Should be true) Request.QueryString.Keys[0]; // == null (Should be "test") Request.QueryString.GetKey(0); // == null (Should be "test") 

这种行为与PHP不同,例如,我可以使用它

 $testExists = isset($_REQUEST['test']); // == True 

Request.QueryString.GetValues(null)将获得没有值的键列表

Request.QueryString.GetValues(null).Contains("test")将返回true

我写了一个扩展方法来解决这个任务:

 public static bool ContainsKey(this NameValueCollection collection, string key) { if (collection.AllKeys.Contains(key)) return true; // ReSharper disable once AssignNullToNotNullAttribute var keysWithoutValues = collection.GetValues(null); return keysWithoutValues != null && keysWithoutValues.Contains(key); } 

Request.QueryString是一个NameValueCollection ,但只有在查询字符串采用通常的[name=value]*格式时才会将项添加到它。 如果没有,它是空的。

如果你的QueryString的forms是?test=value ,那么Request.QueryString.AllKeys.Contains("test")会做你想要的。 否则,你会在Request.Url.Query上进行字符串操作。

我用这个。

 if (Request.Params["test"] != null) { //Is Set } else if(Request.QueryString.GetValues(null) != null && Array.IndexOf(Request.QueryString.GetValues(null),"test") > -1) { //Not set } else { //Does not exist } 
 Request.QueryString.ToString().Contains("test") 

这适用于您正在寻找单个查询字符串参数的特殊情况,例如MyFile.aspx?test

对于更复杂,更一般的案例,其他解决方案会更好。