my c# api takes two parameters, one complex object and one string:
[HttpPost, Route("paramtester")]
public string paramtester(people user, string message) {
return user.name + message;}
how do I pass by a json object in the body? I have tried passing in a serial json object which doesn’t work at all:
{
"user": {
"name": "John Doe",
"age": 30,
"country": "USA"
},
"message": "Hello, World!"
}
this will return:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-40ce97917410bdcff73bb4d8737ed944-2c7f4bf20348d6b7-00",
"errors": {
"name": [
"The name field is required."
],
"address": [
"The address field is required."
],
"message": [
"The message field is required."
]
}
}
2
Answers
You should create a DTO (Data Transfer Object) that includes both:
Then add
[FromBody]
to the endpoint:There is 2 correct approaches:
create a request object that contains a complex object
user
and a silple stringmessage
So your web API become
the other one is as said by Selvin, use the complex parameter
user
from body and the other one as query parameter. So your web API becomeNOTE: the first answer is that it is the simplest and cleanest