4

I have an action

[HttpPatch]
public IHttpActionResult foo(int id, [FromBody]bool boolVariable)
{
 return Ok();
}

I am still debugging and when I try to send some data with Postman I get a strange error

"Message": "The request is invalid.", "MessageDetail": "The parameters dictionary contains a null entry for parameter 'boolVariable' of non-nullable type 'System.Boolean' for method 'System.Web.Http.IHttpActionResult foo(Int32, Boolean)' in 'ProjectName.Controllers.NameController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."

The problem is that it isn't binding boolVariable with my json body... yea I can easily solve the problem with a bind model

  public class FooBindModel
    {
        public bool boolVariable{ get; set; }
    }


public IHttpActionResult foo(int id, FooBindModel bindModel)
{
 return Ok();
}

However it's bugging me why doesn't it bind the variable from the json's body? I am specifying [FromBody] in the action parameters...

john
  • 41
  • 1
  • 3

1 Answers1

6

This is actually a case where you really need to use the often misused [FromBody] attribute. Web Api will by default try to read the request body as an object which makes the [FromBody] attribute redundant when dealing with objects.

But when you have a value type in your request body then you need to tell Web Api that you want to get your value type from the body and that is what [FromBody] does.

So to solve this you should specify the [FromBody] bool boolVariable and only send the bool value in the body, i.e

true

Read more under the Using [FromBody] section

Nae
  • 10,363
  • 4
  • 30
  • 67
Marcus Höglund
  • 13,944
  • 9
  • 42
  • 63