In what cases an object passed to action method equals null?

esam 6 Reputation points
2024-07-21T14:32:38.1+00:00

i have an action method like so:
public IActionResult CreateShirt([FromBody] Person person)

{

// my code

}

some courses checks if the incoming object is null. but using postman i couldn't make person null no matter what i do with the request : no body , malformed json in the body , content-type header missing or wrong ... etc , in all those cases the either framework throw error but the action method is not executed , or the action is executed but the person is an object with default values. no null ever.

the question: can a passed object like this be null? in what cases? should i check the incoming object for null?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,596 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 66,061 Reputation points
    2024-07-21T17:35:49.5466667+00:00

    depends on the content-type. If json, then pass the value null as the body value. If a form post, then by definition the object is created and the post values applied to it.


  2. Jerry Fu - MSFT 741 Reputation points Microsoft Vendor
    2024-07-22T09:55:30.49+00:00

    Hi,

    I recommend you check the Request content directly to confirm if the request is null or just there's issue with the model binding.

            public IActionResult CreateShirt([FromBody] Person person)
            {
                var requestStream = await Request.Content.ReadAsStreamAsync();
                string requestBody;
                using (var reader = new StreamReader(requestStream))
                {
                    requestBody = await reader.ReadToEndAsync();
                }
            }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.