3

I have URL: http://site.com/page.aspx?update

how do I check if that update value is present?

HttpValueCollection treats that as an entity with null key. I have tried:

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

but it gives me a frowny line, because GetValues' argument is decorated with [NotNull].

so I end up doing:

    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;

not the most elegant workaround. Is there a better way to get key-less value from query string?

3 Answers 3

5

You can use

Request.QueryString[null]

to retrieve a comma separated list of keys with no values. For instance, if your url is:

http://mysite/?first&second

then the above will return

first,second

In your case, you could just do something like:

if(Request.QueryString[null] == "update") 
{
    // it's an update
}
Sign up to request clarification or add additional context in comments.

2 Comments

I stil get warning argument decorated with [NotNull] if I don't mind that - I can as well use Request.QeryString.GetValues(null). I wonder if warning is baseless, since I don't see [NotNull] on the argument.
Yeah I think the same thing. It all seems to work OK, so I'm not worrying too much about the warning.
1

if that's the only key you would use

Request.QueryString.ToString() to get the "update" value

Comments

0

I know I'm late to the party, but this a function that I use for this kind of task.

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

You may need to update it so that it is case sensitive, or uses different arguments depending on your purposes, but this has always worked well for me.

1 Comment

I cannot speak for the proc/cons of this solution, but here a one liner of it return request.QueryString.ToString().Split('&').Select(parts => parts.Split('=')).Any(bits => bits[0].Equals(key, StringComparison.OrdinalIgnoreCase));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.