I have an endpoint decorated with [HttpPost]
attribute.
This endpoint url should have one of it's input object's properties coming from the route itself but all other properties should come from the request body.
This is the endpoint decorated with it's routing definition:
[HttpPost]
[Route("{userId}/orders/add")]
public async Task<ActionResult<UserOrderCreationRequest>> CreateOrder(
[FromBody]RequestObject request)
The request object have a property defined like this:
public class RequestObject
{
[FromRoute(Name = "userId")]
public string UserId { get; set; }
public Order order { get; set; }
}
For some reason the UserId is not getting populated and is coming null.
BUT, when I change the [FromBody]
to [FromQuery]
it is working well.
I have also tried removing the [FromBody]
without any replacement and it still didn't work as I got UserId equals null.
Can someone explain this behavior? Why only the
[FromQuery]
gets it to work?
Any other solution that doesn't include creating CustomBinder
will be much appreciated.
CodePudding user response:
It depends on the content type. You must be using application/json content type. In this case you will need to put userId separately and add [FromBody] attribute
[Route("{userId}/orders/add")]
public async Task<ActionResult<UserOrderCreationRequest>> CreateOrder(string userId,[FromBody] Order order)
but if you use application/x-www-form-urlencoded or multipart/form-data form enctype or ajax content-type then this will be working if you remove [FromBody] attribute
[Route("{userId}/orders/add")]
public async Task<ActionResult<UserOrderCreationRequest>> CreateOrder( Order order)
and change your class if you use default end points configuration
public class RequestObject
{
[FromRoute(Name = "id")]
public string UserId { get; set; }
public Order order { get; set; }
}
CodePudding user response:
Ditch the RequestObject
class - you're doing something very weird for binding data.
Instead, bind two different parameters in your CreateOrder
method.
[HttpPost]
[Route("{userId}/orders/add")]
public async Task<ActionResult<UserOrderCreationRequest>> CreateOrder(
string userId, // [FromRoute] is optional here
[FromBody] Order order)
{
}