簡體   English   中英

如何在 C# HttpPost 方法中解析 JSON 正文

[英]How to parse JSON body in C# HttpPost method

我想解析一個 JSON 主體並在 C# 中的 HttpPost 方法中返回內容。

JSON 主體包含以下信息:

{
    "name": "John",
    "age": "20"
}
[HttpPost]
public async Task<IActionResult> Test() 
{
return new JsonResult(new { items = new string[] { name, age } });

}

我希望方法返回:

John 20

嘗試這個

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

}

您不需要異步,因為您在操作中沒有任何異步方法

如果我的問題正確,您只想返回John 20的字符串,那么您可以直接使用:

返回 OK($"{name} {age}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM