❔ Binding a DTO from route and body
I have been trying to do this for the last 5 years. I want to be able to send something like a put request with the route: 'api/user/{id}' and send a body with data to update like
{"username": "newUsername"}
and have an endpoint like this:
[HttpPut("{id}")]
public async Task<IActionResult> UpdateUser(UpdateUserDTO dto)
where the DTO would look like this:
public record UpdateUserDTO(int Id, string userName)
and just have it bind without having to accept the id as another parameter in the UpdateUser endpoint and then set it in the DTO. I have tried setting the [FromRoute] and [FromBody] both in the DTO class and in the UpdateUser parameters.
Really hope someone can shed some light on this.4 Replies
Afaik you can't do this.
Route params can fill an object or be used as is, body is always an object like here. You can't combine them automagically
I thought it was just me being stupid. For me that seems like an oversight as in alot of rest calls, you send an id in route and a body with changes/new entity
its not an oversight. you can easily build that joint object yourself
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.