Web API 将 JSON 对象转换为简单参数 [英] Web API translate JSON object into simple parameters
问题描述
如果我像这样将 JSON 数据(通过 POST)发送到 .Net Core Web API
If I am sending JSON data (via POST) to a .Net Core Web API like this
{ a: "a", b: "b" }
我需要做什么才能拥有这样的控制器方法?
What do I need to do to have a controller method like this?
[HttpPost]
public async Task SometMethod(string a, string b)
{
return Ok();
}
通常,所有教程和文档都说您需要定义一个类并使用 [FromBody]
属性.但是,如果没有我真正不需要的额外课程,我怎么办?
Normally, all tutorials and docs say that you need to define a class and use [FromBody]
attribute. But how can I make do without extra classes that I don't really need?
推荐答案
首先,你的 json 应该是:
Firstly,your json should be:
{
"a":"a",
"b":"b"
}
您可以以 JObject
的形式接收数据,而不是像下面这样的类:
You could receive data as JObject
instead of a class like below:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpPost]
public void Post(JObject data)
{
//get the property value like below
var data1 = data["a"].ToString();
var data2 = data["b"].ToString();
}
}
结果(为了方便区分值和属性名,我把a
改为aaa
,b
改为bbb
):
Result (For easily distinguish value and property name,I change a
to aaa
and b
to bbb
):
这篇关于Web API 将 JSON 对象转换为简单参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!