'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.
If you have query parameter with no value. For example:
/products?pageNo=1&pageSize=You will find yourself getting an exception thrown for
pageSizeparameter asCountproperty onStringValueswill give you value 1, but underlying_valueis""(empty string) and_valuesisnull. Note - Exception happens you are trying to convert or access values from IQueryCollection)Using
TryGetValuewill get you value safely out ofStringValuesbut if it is null (like in case ofpageSizeparameter above), You will have hard time figuring out why can't you convertStringValuesto simpleStringor why can not compare withnullto do further operations on it like validations etc.To do any checking on
StringValuestype, 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 |
