1

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
  • is this a question asp.net core, or asp.net web api? Commented Apr 3, 2017 at 18:54

3 Answers 3

4

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" 
   }
 ]
Sign up to request clarification or add additional context in comments.

2 Comments

I tried changing it to ` [ { "LocationId": "111", "ProductId": 110, "Sku": "11131-LJK" } ] ` and it also doesn't work
Well, now it works, no idea why before it was not taking the array correctly. Murphy's law I guess. Thanks.
0

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

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.