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...

2
  • How do you specify the body when you posting to the api? Commented Aug 21, 2017 at 19:26
  • @marcus {"boolVariable":true} Commented Aug 22, 2017 at 17:27

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.