Search code examples
c#json.net-corehttp-postwebapi

How to parse JSON body in C# HttpPost method


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

Solution

  • 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