【发布时间】:2021-09-21 08:51:45
【问题描述】:
如何在没有模型绑定的情况下使用 ASP.NET Core WebAPI 处理 json 请求?
我有一百多个 API 需要转入 ASP.NET Core WebAPI,但是因为数量太多,我无法为每个 API 设计模型。
另外我还需要使用Swagger,所以不能像IActionResult Post(string json)或者IActionResult Post(JObject obj)那样使用字符串解析。
控制器代码(有bug):
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
public class Person { public int Age { get; set; } }
[HttpPost]
public IActionResult Post([FromBody] string name, Person person)
{
return Ok(new
{
Name = name,
person.Age
});
}
}
邮递员:
POST /Test HTTP/1.1
Host: localhost:5000
Content-Type: application/json
Content-Length: 68
{
"Name": "Test",
"Person": {
"Age": 10
}
}
当前 API 接口:
bool InsertPoint(PointInfo point);
bool[] InsertPoints(PointInfo[] points);
bool RemovePoint(string pointName);
bool[] RemovePoints(string[] pointNames);
string[] Search(SearchCondition condition, int count);
...
我想在控制器中做什么:
[HttpPost]
[SomeJsonBodyAttribute]
public IActionResult InsertPoint(PointInfo point);
[HttpPost]
[SomeJsonBodyAttribute]
public IActionResult InsertPoints(PointInfo[] points);
[HttpPost]
[SomeJsonBodyAttribute]
public IActionResult RemovePoint(string pointName);
[HttpPost]
[SomeJsonBodyAttribute]
public IActionResult RemovePoints(string[] pointNames);
[HttpPost]
[SomeJsonBodyAttribute]
public IActionResult Search(SearchCondition condition, int count);
...
我想在请求中做什么:
- 移除点
POST /Point/RemovePoint HTTP/1.1
Content-Type: application/json
{
"pointName": "Test"
}
- 搜索
POST /Point/Search HTTP/1.1
Content-Type: application/json
{
"condition": {
...
},
"count": 10
}
【问题讨论】:
-
嗨@yejinmo,为什么不使用JObject?
-
此链接可能对您有所帮助:stackoverflow.com/questions/40853188/…
-
您可以查看动态作为参数。但是,我会质疑移动数百个 api 而又不想拥有专用模型的基本原理。您如何处理每个控制器中的数据而不会有错位的风险,尤其是在有一百个 api 的情况下?
-
您的代码中有错误。你想修复这个错误或其他什么?如果您想使用 Swagger,则无法使用任何动态模型。你必须决定什么更重要。
-
@Rena 如果我使用 JObject,我无法使用 Swagger 生成文档。
标签: asp.net-core asp.net-web-api asp.net-core-webapi