C# .net core web api post parameter always null

橙三吉。 提交于 2019-12-24 09:02:28

问题


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



来源:https://stackoverflow.com/questions/43192053/c-sharp-net-core-web-api-post-parameter-always-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!