【问题标题】:ASP.Net MVC : Get query values with no keyASP.Net MVC:获取没有键的查询值
【发布时间】:2011-04-13 17:34:03
【问题描述】:

我有网址:http://site.com/page.aspx?update

如何检查更新值是否存在?

HttpValueCollection 将其视为具有null 键的实体。我试过了:

var noKeyValues = Request.QueryString.GetValues(null);
if (noKeyValues != null && noKeyValues.Any(v=>v==update)) ...

但它让我皱眉头,因为 GetValues 的参数用 [NotNull] 修饰。

所以我最终做了:

    var queryValuesWithNoKey =
            Request.QueryString.AllKeys.Select((key, index) => new { key, value = Request.QueryString.GetValues(index) }).Where(
                    item => item.key == null).Select(item => item.value).SingleOrDefault();
    if (queryValuesWithNoKey != null && queryValuesWithNoKey.Any(v => v.ToLower() == "update")) live = true;

不是最优雅的解决方法。有没有更好的方法从查询字符串中获取无键值?

【问题讨论】:

    标签: asp.net-mvc query-string


    【解决方案1】:

    你可以使用

    Request.QueryString[null]
    

    检索没有值的逗号分隔的键列表。例如,如果您的网址是:

    http://mysite/?first&second

    那么上面会返回

    first,second
    

    在你的情况下,你可以这样做:

    if(Request.QueryString[null] == "update") 
    {
        // it's an update
    }
    

    【讨论】:

    • 如果我不介意,我仍然会收到警告 argument decorated with [NotNull] - 我也可以使用 Request.QeryString.GetValues(null)。我想知道警告是否毫无根据,因为我没有在论点上看到 [NotNull]。
    • 是的,我也这么认为。一切似乎都正常,所以我不太担心警告。
    【解决方案2】:

    如果这是你唯一会使用的钥匙

    Request.QueryString.ToString() 获取“更新”值

    【讨论】:

      【解决方案3】:

      我知道我迟到了,但这是我用于此类任务的功能。

      internal static bool HasQueryStringKey(HttpRequestBase request, string key)
      {
          // If there isn't a value, ASP will not recognize variable / key names.
          string[] qsParts = request.QueryString.ToString().Split('&');
          int qsLen = qsParts.Length;
          for (int i = 0; i < qsLen; i++)
          {
              string[] bits = qsParts[i].Split('=');
              if (bits[0].Equals(key, StringComparison.OrdinalIgnoreCase))
              {
                  return true;
              }
          }
      
          return false;
      }
      

      您可能需要对其进行更新,使其区分大小写,或者根据您的目的使用不同的参数,但这对我来说一直很有效。

      【讨论】:

      • 我不能代表这个解决方案的过程/缺点,但这里是它的一个衬里return request.QueryString.ToString().Split('&amp;').Select(parts =&gt; parts.Split('=')).Any(bits =&gt; bits[0].Equals(key, StringComparison.OrdinalIgnoreCase));
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多