'Why is StringValues used for Request.Query values?

Let's say I have some url that looks like this: www.myhost.com/mypage?color=blue

In Asp.Net Core, I'd expect to get the color query parameter value by doing the following:

string color = Request.Query["color"];

But it turns out that the Request.Query["color"] returns a value of type StringValues rather than string. Why is that?

Apparently the StringValues type can hold an array of strings and includes support for implicit conversion to string[] which is cool but why is that needed for a query param value?

Having to get the value like this seems odd:

string color = Request.Query["color"].ToString();

And worse, checking for a value to see if a query param is specified can no longer be done like so

  if(Request.Query["color"] == null) { 
      //param was not specified
  }

but instead must be checked like so

 if(Request.Query["color"].Count == 0) { 
      //param was not specified
 }

Since a single query parameter can't have multiple values (as far as I know) why does Request.Query["color"] return a StringValues object rather than a string?



Solution 1:[1]

Because your query can look like this:

www.myhost.com/mypage?color=blue&color=red&color=yellow

And you get all those color values from the one Request.Query["color"] parameter

Solution 2:[2]

Just posting for curious souls and probably little do with question. Just cautionary note.

I found myself in similar issue. There are couple other issues with this type.

  1. If you have query parameter with no value. For example: /products?pageNo=1&pageSize=

    You will find yourself getting an exception thrown for pageSize parameter as Count property on StringValues will give you value 1, but underlying _value is "" (empty string) and _values is null. Note - Exception happens you are trying to convert or access values from IQueryCollection)

  2. Using TryGetValue will get you value safely out of StringValues but if it is null (like in case of pageSize parameter above), You will have hard time figuring out why can't you convert StringValues to simple String or why can not compare with null to do further operations on it like validations etc.

  3. To do any checking on StringValues type, use methods provided by the type.

To check for null or empty use - StringValues.IsNullOrEmpty(StringValues value)

Solution 3:[3]

If you want the first string and are not expecting multiple values just do:

Request.Query["color"][0]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jamiec
Solution 2 Community
Solution 3 Tono Nam