简体   繁体   中英

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

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

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}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM