Aar*_*ush 18 c# asp.net .net-3.5
在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"
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想要检查是否存在测试,所以我可以调用页面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
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想要的是一个布尔值,告诉我测试变量是否存在于字符串中.
我想我可以使用正则表达式检查字符串,但我很好奇是否有人有更优雅的解决方案.
我尝试过以下方法:
//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")
Run Code Online (Sandbox Code Playgroud)
这种行为与PHP不同,例如,我可以使用它
$testExists = isset($_REQUEST['test']); // == True
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 25
Request.QueryString.GetValues(null) 将获得没有值的键列表
Request.QueryString.GetValues(null).Contains("test") 将返回真实
我写了一个扩展方法来解决这个任务:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22643 次 |
| 最近记录: |