Search code examples
c#.netasp.net-coreasp.net-web-api-routingasp.net-core-webapi

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?


Solution

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