Can a controller ever accept a null parameter value?

Viewed 329

If I had a controller method like so:

public ActionResult<Item> GetItem(RequestHeaderBase headers, RequestObject request)

Can I always assume that the headers object and request object will be instantiated (not null)?

(I would appreciate any links to deeper reading regarding how this works regardless of the answer)

Here is an example of what I mean

Here I call the request: https://localhost:44360/weatherforecast and you can see the input object has been instantiated despite me not providing the query string. enter image description here

Another example, this time with data from the body: enter image description here enter image description here

In both cases, you can see with my debugging, no matter what the objects are instantiated, even if I don't provide any data in the request.

Now I've seen code that checks if this data is null in some of our applications, I believe this code is irrelevant, and so can be removed.

2 Answers

if it is a reference object ( not a value) it will be always instantiated. Each object property will have a default value. This is why any class that are using for action input parameter should have default or parameter less constructor. Otherwise it will cause an exception. Only when object is created, controller trying to assign values to the object properties according to the http request. But be carefull, only the top level will be instantiated. If you have another complicated properties inside of this object, they will be instantied and have a default value according to the type. For example, List will be null (default value), not an empty list. Nullable integer property will ne null, not nullable 0, and so on. But you can assign default values you need in the constructor for example.

even if you change the action signature to this

public ActionResult<Item> GetItem(RequestHeaderBase headers=null, RequestObject request=null)

they still will be instantiated, each property will have a default value according to the type.

Can I always assume that the headers object and request object will be instantiated (not null)?

no, they can be null.

Related