C# .net core web api post parameter always null

2019-07-30 06:00发布

问题:

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?

回答1:

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" 
   }
 ]


回答2:

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

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


回答3:

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