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?
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.
Please note that we are able to send [FromBody] parameter in HTTP GET Request input.
Simply add parameterName = null in your route parameter. Another option is add an overload. Have 2 function names receive different parameters.
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.
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)
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) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With