【问题标题】:Json Request Without Model Binding In ASP.NET Core WebAPIASP.NET Core WebAPI 中没有模型绑定的 Json 请求
【发布时间】: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


【解决方案1】:

请务必在您的项目中添加 Newtonsoft 支持。您可以参考以下答案:

https://stackoverflow.com/a/65101721/11398810

然后你可以得到如下数据:

[HttpPost]
public IActionResult Post([FromBody] JObject obj)
{
    //for list model:
    //obj["Person"][0]["Age"].ToString()
    return Ok(new { Name = obj["Name"].ToString(), Age = obj["Person"]["Age"].ToString() });
}

带json:

{
    "Name": "Test",
    "Person": {
        "Age": 10
    }
}

结果:

【讨论】:

  • 这是一个折中的方案,但它不能:1.基于参数列表的方法绑定2.在Swagger中自动生成参数描述
  • 不可能自动满足您的新要求,因为您不想为它们创建模型。 JObject 是解决原始问题的最快方法。
猜你喜欢
  • 2018-03-27
  • 1970-01-01
  • 2018-04-27
  • 1970-01-01
  • 2020-09-04
  • 2013-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多