I'm in the process of implementing a REST API using ASP.NET Core Web API (v3.1). At the moment I'm not sure how to distinguish between an "undefined" value and a "null" value when passed through a query string in an URL.
As an example, let's assume that the API manages users, that all have a first name and a last name. In addition all users may have a middle name.
The REST API allows querying for these users like so:
GET api/user?lastName=doe
(this returns a collection of user resources, that have the last name "Doe"). The related controller class could look like this:
[HttpGet]
public IActionResult GetUsers(string firstName, string lastName, string middleName)
{
// Search database for users
// Ignore firstName and middleName, because they are null
}
My problem arises, when queries include the middle name:
GET api/user?middleName=null&firstName=john
This query (where middleName
is explicitly set to null
) should return users with the first name "John" and NO middle name. In contrast the request
GET api/user?firstName=john
(where middleName
is undefined
) should return all users with the first name "John" regardless of whether they have a middle name or not.
In both cases the middleName
parameter inside my controller method is set to null
. How can I distinguish between these queries in my controller?
EDIT:
My example is misleading and does not behave as I expected it to, because
GET api/user?middleName=null&firstName=john
sets middleName
to the string value "null"
instead of null
(as in nothing).
I still want to let clients search for users without a middle name (where the database value for the middle name is NULL). How can this be passed through the URL and processed further by the controller?