Why is StringValues used for Request.Query values?

后端 未结 4 1494
粉色の甜心
粉色の甜心 2020-12-25 10:08

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 fo

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-25 10:30

    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)

提交回复
热议问题