Post FromBody Always Null

痞子三分冷 提交于 2019-11-30 13:40:04

问题


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?


回答1:


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)



回答2:


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 binded so it will be null.

if (ModelState.IsValid) { ... }



回答3:


if you want to send two o more models you should use this example, this works for me, good luck

    [HttpPost]
    public async Task<ActionResult> addUsuario([FromBody] Newtonsoft.Json.Linq.JObject datos)
    {
        Usuarios user = datos["usuario"].ToObject<Usuarios>();
        Empresas empresa = datos["empresa"].ToObject<Empresas>();
       return  Json(await _srv.addUsuario(user, empresa));
    }



回答4:


I know it is not related to your case, still, I am posting my answer here. It is a silly mistake that I had done in my code. I just copied, one of my Get requests and changed it to Post request, and forgot to decorate the parameter with [FromBody]. If anyone else is having the same problem, please make sure that you are decorating the parameter with [FromBody].

[HttpPost]
public IApiResponse Update([FromBody] User user) {
 if (user == null) return new ApiBadRequestResponse(ModelState);
 return _userService.Post(user) ? new ApiOkResponse(user) : new ApiResponse(500);
}


来源:https://stackoverflow.com/questions/42277639/post-frombody-always-null

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