'Combine [FromBody] and [FromRoute] attributes in one model
I am trying to create model, which I could use for Body and Route at once. I found solution here, but I would like to move it little bit further. Not using extra "body" class, but include everything in one class. I tried this, but it does not work.
public class Car
{
[Required, FromRoute]
public int CarId { get; set; }
[Required, FromBody]
public string UpdatedBy { get; set; }
[Required, FromBody]
public string Colour { get; set; }
[Required, FromBody]
public string Wheels { get; set; }
[Required, FromBody]
public DateTime UpdatedDate { get; set; }
}
I am trying to use it as input for PUT method:
public async Task<IActionResult> CarUpdate(Car car, CancellationToken cancellationToken)
But I would like to have it like this:
Is it possible? Thank you.
Solution 1:[1]
Unfortunately you can only use FromBody once, you are trying to use it multiple times , this is why is not working. This looks akward but will be working
public async Task<IActionResult> CarUpdate(CarRoute carRoute, CancellationToken cancellationToken)
but you will have to add this to startup
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressInferBindingSourcesForParameters = true;
});
classes
public class CarRoute
{
[FromRoute]
public int CarId { get; set; }
[FromBody]
public Car Car { get; set; }
}
public class Car
{
public int CarId { get; set; }
public string Name { get; set; }
public string Colour { get; set; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge |


