Post FromBody Always Null

后端 未结 6 1436
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 03:01

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:

         


        
相关标签:
6条回答
  • 2020-12-29 03:12

    Also, make sure those variables inside your parameter class are declared as Public, (or they'll just keep returning as null)..

    0 讨论(0)
  • 2020-12-29 03:18

    Another reason for the model binding to fail (always null) is if the data type for a property doesn't match. For example here is a simple model:

    public class MyService {
        public string JobId { get; set; }
        public int ServiceType {get; set;}
    }
    

    And here is some json that doesn't match:

    {"JobId":1, "ServiceType":1}
    

    I got caught with this when I was retrieving the JobId using jquery's .data function, it was automatically converting it to an int. Fixed it by using .attr function instead.

    0 讨论(0)
  • 2020-12-29 03:21

    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 a 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);
    }
    
    0 讨论(0)
  • 2020-12-29 03:23

    If you want to send two or more models, you should use this example:

    [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));
    }
    
    0 讨论(0)
  • 2020-12-29 03:25

    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)
    
    0 讨论(0)
  • 2020-12-29 03:25

    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) { ... }
    
    0 讨论(0)
提交回复
热议问题