Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post FromBody Always Null

I've got a new API that I'm building with ASP.NET Core, and I can't get any data POST'ed to an endpoint.

Here's what the endpoint looks like:

[HttpPost] [Route("StudentResults")] public async Task<IActionResult> GetStudentResults([FromBody]List<string> userSocs, [FromBody]int collegeId) {     var college = await _collegeService.GetCollegeByID(collegeId);     // var occupations = await _laborMarketService.GetOccupationProgramsBySocsAndCollege(userSocs, college);     return Ok(); } 

And here's what my payload that I'm sending through Postman looks like:

{     "userSocs": [             "291123",             "291171",             "312021",             "291071",             "152031",             "533011"         ],     "collegeId": 1 } 

I'm making sure that I have postman set as a POST, with Content-Type application/json. What am I doing wrong?

like image 308
Alex Kibler Avatar asked Feb 16 '17 15:02

Alex Kibler


People also ask

What does FromBody mean?

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.

Can we use FromBody with Httpget?

Please note that we are able to send [FromBody] parameter in HTTP GET Request input.

How do I pass a null parameter in Web API?

Simply add parameterName = null in your route parameter. Another option is add an overload. Have 2 function names receive different parameters.

What is FromBody attribute?

The [FromBody] attribute which inherits ParameterBindingAttribute class is used to populate a parameter and its properties from the body of an HTTP request. The ASP.NET runtime delegates the responsibility of reading the body to an input formatter.


2 Answers

You get always null because you need to encapsulate all your post variables inside only one object. Like this:

public class MyPostModel {     public List<string> userSocs {get; set;}     public int collegeId {get; set;} } 

and then

public async Task<IActionResult> GetStudentResults([FromBody] MyPostModel postModel) 
like image 53
Tinwor Avatar answered Sep 23 '22 10:09

Tinwor


If the model is null, check:

1) Where the data is sent: body, form? and based on that add the decorator to the action. For ex:

[HttpPost] public JsonResult SaveX([FromBody]MyVM vm) { ... } 

2) Check ModelState: if it's invalid the vm will not be bound so it will be null.

if (ModelState.IsValid) { ... } 
like image 20
Francisco Goldenstein Avatar answered Sep 23 '22 10:09

Francisco Goldenstein