Jonathan
Jonathan

Reputation: 107

C# .net core web api post parameter always null

So this is driving me nuts. I'm doing something very simple sending POST request to my web api. The endpoint is set up as follows:

[HttpPost]
[Route("locations")]
public async Task<IActionResult> PostLocations([FromBody]IEnumerable<Location>locations)

and I'm making the call as follows:

http://localhost:60254/api/Fetch/locations
With the body 
{
  "Locations": [
    { 
        "LocationId": "111", 
        "ProductId": 110, 
        "Sku": "11131-LJK" 
    }
  ]
}

And header: content-type: application/json

now again, this is VERY simple something that should work out of the box and this fricking framework change is messing everything up.

Now, if I get the HttpContext and read the body stream directly

    using (StreamReader reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8))
    {
      string  body = reader.ReadToEnd();
    }

I can see the body being sent correctly, I have a super well formed json that I can transform into whatever I want. So the question is what am I missing that this endpoint doesn't work?

What configuration the web api project template is not adding out of the box for this to work?

Upvotes: 1

Views: 3233

Answers (3)

ChrisBellew
ChrisBellew

Reputation: 1174

For others...make sure your [FromBody] model and all child classes have parameterless constructors

Upvotes: 0

Victor Hurdugaci
Victor Hurdugaci

Reputation: 28425

Your payload is not a list of Location but an object with a Locations property that's a list.

Instead of

{
  "Locations": [
   { 
      "LocationId": "111", 
      "ProductId": 110, 
      "Sku": "11131-LJK" 
   }
 ]
}

use

 [
   { 
     "LocationId": "111", 
     "ProductId": 110, 
     "Sku": "11131-LJK" 
   }
 ]

Upvotes: 4

Mike_G
Mike_G

Reputation: 16512

Don't pass a json object, pass a stringified one:

var location = [
{ 
 "LocationId": "111", 
 "ProductId": 110, 
 "Sku": "11131-LJK" 
  }
]
var dataToPost = JSON.stringify(location);

Upvotes: 0

Related Questions