locked
model binding in AspNet Core WebApi? RRS feed

  • Question

  • User-154227990 posted

    I am working on web API .Net core 3.0. HTTP Post Model binding is partially working. It does not bind departments.

    Using postman, I am passing below JSON data.

    JSON Data:

    [
      {
        "refid": "9a6383b7-f581-405f-9cd4-4adf91052ca6",
        "firstname": "Test",
        "departments": [
          {
            "departmentid": "3089e0d5-476f-407a-9458-949d058123f"
          },
          {
            "departmentid": "4089e0d5-476f-407a-9458-949d058123f"
          },
        ]
      },
      {
        "refid": "926383b7-f581-405f-9cd4-42df91052ca6",
        "firstname": "Test",
        "departments": [
          {
            "departmentid": "3089e0d5-476f-407a-9458-949d7d08123f"
          },
          {
            "departmentid": "3089e0d5-456f-407a-9458-949d7d08123f"
          }
        ]
      }
    ]
    

    WebApi Endpoint:

    [HttpPost("employees")]
    public async Task<IActionResult> CreateEmployee([FromBody] IEnumerable<EmployeeDto> employeeCollection)
    {
       ***HERE IT ONLY BIND EmployeeDto but not departments** not sure what is wrong***
    }
    

    C# Code

    public class EmployeeDto {
    
            public Guid RefId { get; set; }
            public string FirstName { get; set; }
    
            List<Department> Departments { get; set; }
        }
    
        public class Department {
            public Guid departmentId { get; set; }
        }
    Tuesday, June 1, 2021 5:54 AM

Answers

  • User287926715 posted

    Hi learningcode,

    The first problem is that your Json format is incorrect, you need to remove the red ",".

    "departments": [
          {
            "departmentid": "3089e0d5-476f-407a-9458-949d058123f"
          },
          {
            "departmentid": "4089e0d5-476f-407a-9458-949d058123f"
          },

    The second one needs to add the public modifier to List<Department> Departments {get; set;}.

     public List<Department> Departments { get; set; }

    The third problem is that the departmentid passed in is not of type Guid.

    I used the following method to determine whether it is a Guid type, and the results are as follows:

    Best Regards,

    ChaoDeng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 1, 2021 8:21 AM