Check if unassigned variable exists in Request.QueryString

后端 未结 5 635
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 05:59

Within the context of an ASP.NET page, I can use Request.QueryString to get a collection of the key/value pairs in the query string portion of the URI.

For example, if I

相关标签:
5条回答
  • 2021-02-07 06:14

    Request.QueryString.GetValues(null) will get a list of keys with no values

    Request.QueryString.GetValues(null).Contains("test") will return true

    0 讨论(0)
  • 2021-02-07 06:14

    I use this.

    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
    }
    
    0 讨论(0)
  • 2021-02-07 06:15

    I wrote an extension method to solve this task:

    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);
    }
    
    0 讨论(0)
  • 2021-02-07 06:18
    Request.QueryString.ToString().Contains("test")
    

    This works in the special case where you're looking for a single querystring parameter, e.g. MyFile.aspx?test

    For more complex, general, cases then other solutions would be better.

    0 讨论(0)
  • 2021-02-07 06:36

    Request.QueryString is a NameValueCollection, but items are only added to it if the query string is in the usual [name=value]* format. If not, it is empty.

    If your QueryString was of the form ?test=value, then Request.QueryString.AllKeys.Contains("test") would do what you want. Otherwise, you're stuck doing string operations on Request.Url.Query.

    0 讨论(0)
提交回复
热议问题