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?
Request.Query
, use model binding instead.var color = Request.Query["color"]; if (StringValues.IsNullOrEmpty(color)) { // do something };