I want to parse a JSON body and return the contents in a HttpPost method in C#.
The JSON body contains the following information:
{
"name": "John",
"age": "20"
}
[HttpPost]
public async Task<IActionResult> Test()
{
return new JsonResult(new { items = new string[] { name, age } });
}
I want the method to return:
John 20
CodePudding user response:
try this
public class ViewModel
{
public string Name {get; set;}
public int Age {get; set;}
}
[HttpPost]
public JsonResult Test([FromBody ViewModel model])
{
return new JsonResult(new { name= model.Name, age=model.Age } });
}
you don' t need async since you don't have any async methods inside of the action
CodePudding user response:
If I'm getting the question correctly, you want only to return string of John 20 then you can directly use:
return Ok($"{name} {age}")