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

时间:2013-02-15 19:36:12

标签: 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"
}

理想情况下,我想要检查是否存在 test ,因此我可以使用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

6 个答案:

答案 0 :(得分:25)

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

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

答案 1 :(得分:5)

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

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);
}

答案 2 :(得分:2)

Request.QueryStringNameValueCollection,但如果查询字符串采用通常的[name=value]*格式,则只会将项目添加到其中。如果没有,它是空的。

如果您的QueryString格式为?test=value,那么Request.QueryString.AllKeys.Contains("test")就能满足您的需求。否则,您将无法在Request.Url.Query上执行字符串操作。

答案 3 :(得分:2)

我用它。

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
}

答案 4 :(得分:1)

试试这个,它解决了我的问题! 它将计算查询字符串是否有值或为空,然后您可以使用 Key 检查所需的查询字符串值。

  if (!Page.IsPostBack)
        {
           if (Request.QueryString.Count > 0)
            {
                if (Request.QueryString["departmentId"] != null)
                {
                    GetSurveyByDeptAndStatus(departmentId: Request.QueryString["departmentId"], status: "Not Surveyed");
                    rbListEmpsSurvey.Items[1].Selected = true;
                }

                else if (Request.QueryString["SurveyStatus"] != null)
                {
                    SatisfactionStatus = Request.QueryString["SurveyStatus"] "";
                    GetSurveyByDeptAndStatus(status: SatisfactionStatus);
                    GetDepartments();
                }}}

答案 5 :(得分:-1)

Request.QueryString.ToString().Contains("test")

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

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