【问题标题】:Check if unassigned variable exists in Request.QueryString检查 Request.QueryString 中是否存在未分配的变量
【发布时间】:2013-01-31 20:41:49
【问题描述】:

在 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 调用该页面并获得一个布尔值,告诉我是否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

【问题讨论】:

  • 你为什么不能只检查nullIf(Request.QueryString["test"] != null)
  • @JonH:因为Request.QueryString["test"] 返回null,无论查询字符串中是否存在测试。
  • 嗯?我不确定你的意思,如果它在查询字符串中没有看到 test ,它只会返回 == null ,否则它会返回 != null ,如果是这样,你可以获取 test 的值。我没有看到问题。
  • @JonH:我不想检查 test 的值,只是想看看它是否存在。例如,我希望 ?testtest=anyvalue 都返回 true,但任何其他 (?differentkey=anyvalue) 都返回 false

标签: c# asp.net .net-3.5


【解决方案1】:

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

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

【讨论】:

  • 你比我少了几秒钟 :-) 我不得不查看源代码才能发现这种奇怪的行为。
  • 我收到了 System.ArgumentNullException: Value cannot be null. 错误。
  • 为了避免 ArgumentNullException 使用这个: if (Request.QueryString.Count > 0 && Request.QueryString.GetValues(null).Contains("test"))
  • 对于上面的代码,请注意这将适用于任何包含“test”的查询。例如:“?hello=test。如果你想更具体地使用这个:Request.QueryString.ToString().Split('&').Any(x => x.Split('=')[0] = =“测试”)
  • 要删除 NRE,您可以使用 (Request.QueryString.GetValues(null) ?? new string[0]).Contains(key) 我将其包装在类似于 @DarkDaskin 答案的扩展方法中
【解决方案2】:

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

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

【讨论】:

  • +1 好答案。从 R#8 开始,您不再需要禁用提示,看来他们更新了对 GetValues(null) 的分析。我可以指出的另一件事是,不要忘记重载 Contains(key, StringComparer.OrdinalIgnoreCase) 以避免区分大小写。
【解决方案3】:

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

如果您的QueryString?test=value 的形式,那么Request.QueryString.AllKeys.Contains("test") 会做您想做的事。否则,您将无法在 Request.Url.Query 上执行字符串操作。

【讨论】:

    【解决方案4】:

    我用这个。

    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
    }
    

    【讨论】:

      【解决方案5】:

      试试这个,它解决了我的问题! 它将计算查询字符串是否有值或为空,然后您可以使用 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();
                      }}}
      

      【讨论】:

        【解决方案6】:
        Request.QueryString.ToString().Contains("test")
        

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

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

        【讨论】:

        • 嗯...它可以工作,但它不是很可靠;它不会通过一个像样的单元测试。公认的答案仍然是最好的。我想看看查询字符串是否包含一个名为test 的变量(它是否包含一个值——例如:?test?test=anyvalue 都返回true)。检查查询字符串中是否存在字符串test 可能会产生误报。例如:?a=test - 变量名是a,这不是我要找的。 ?bestest=10 也会产生误报。
        • 好点虽然对于我的用例来说很好。我想可以在原始查询字符串中抛出一个正则表达式。
        • 正则表达式示例:(?
        • 示例测试查询字符串(正则表达式匹配三个正确的情况):test&aaa=tester&test1=test&mytest=test&test&xxxxx&test=test
        • 是的,你也可以使用正则表达式来解析 HTML。 ;-) codinghorror.com/blog/2008/06/…
        猜你喜欢
        • 2011-07-25
        • 1970-01-01
        • 2014-09-08
        • 2012-07-19
        • 2022-07-05
        • 2017-02-13
        • 2011-12-19
        • 2020-09-30
        相关资源
        最近更新 更多