Reputation: 43
How can use ASP.NET Core WebAPI process json request without model binding?
I have more than one hundred APIs that need to be transferred to ASP.NET Core WebAPI, but I cannot design a model for each API because the number is too much.
In addition, I also need to use Swagger, so I cannot use string parsing like IActionResult Post(string json)
or IActionResult Post(JObject obj)
.
Controller Code(with 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
});
}
}
Postman:
POST /Test HTTP/1.1
Host: localhost:5000
Content-Type: application/json
Content-Length: 68
{
"Name": "Test",
"Person": {
"Age": 10
}
}
Current API Interface:
bool InsertPoint(PointInfo point);
bool[] InsertPoints(PointInfo[] points);
bool RemovePoint(string pointName);
bool[] RemovePoints(string[] pointNames);
string[] Search(SearchCondition condition, int count);
...
What i want to do in controller:
[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);
...
What i want to do in request:
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
}
Upvotes: 0
Views: 3019
Reputation: 36575
Be sure add Newtonsoft support in your project.You could refer to the following answer:
https://stackoverflow.com/a/65101721/11398810
Then you could get data like below:
[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() });
}
With json:
{
"Name": "Test",
"Person": {
"Age": 10
}
}
Upvotes: 2