Reputation: 73
I'm trying to send a List to my controller via Web API. I'm sending it as JSON via Postman. I'm 100% sure the JSON is correctly formatted. Still the usersList
ends up null
. I've tried without the [FromBody]
attribute also.
The controller name is UserController
, so the url is api/user/
. Method used is Put
.
public IHttpActionResult Put([FromBody]List<UserVm> usersList)
{
if (usersList.Count > 0)
{
_userService.UpdateUserRoles(usersList);
return Ok();
}
return BadRequest();
}
public class UserVm
{
public int Id { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public string Token { get; set; }
public string Icao { get; set; }
public string RefreshToken { get; set; }
public int ExpiresIn { get; set; }
public List<Role> Roles { get; set; }
}
[
{
"id": 0,
"username": "banji",
"name": "baji",
"token": "bajz",
"icao": "poffe",
"refreshtoken": "konna",
"expiresin": 0,
"roles": [{
"id": 0,
"department": "asd",
"isadmin": false
}]
},
{
"id": 0,
"username": "banji",
"name": "baji",
"token": "bajz",
"icao": "poffe",
"refreshtoken": "konna",
"expiresin": 0,
"roles": [{
"id": 0,
"department": "asd",
"isadmin": false
}]
}
]
Suggestions on what I'm doing wrong are much appreciated.
Upvotes: 0
Views: 274
Reputation: 73
I found the solution to my problem. I had forgotten to have an parameterless constructor..
Upvotes: 0
Reputation: 1876
I just copied what you posted and tried here. It works fine.
And the code:
public class UserVm
{
public int Id { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public string Token { get; set; }
public string Icao { get; set; }
public string RefreshToken { get; set; }
public int ExpiresIn { get; set; }
public List<Role> Roles { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Department { get; set; }
public bool IsAdmin { get; set; }
}
public class UserController : ApiController
{
public IHttpActionResult Put([FromBody]List<UserVm> usersList)
{
if (usersList.Count > 0)
{
//_userService.UpdateUserRoles(usersList);
return Ok();
}
return BadRequest();
}
}
The postman data looks the same you posted too:
Do you have a default api route? Like:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
PS: It's a nice practice to use /resource/id when you use put. You are saying that you are going to change the resource with the given id, or you are going to create a resource with that id. The verb PUT is idempotent, so it should have always the exact same return. Thats why it's used more offen to do updates intead of creating resources.
Upvotes: 3