Is it possible to implement follow:
I have a controller, that contains several methods and using as API. For GET requests I can just send params in url query and use it in a method body, but for POST method I just get json object in a FromBody param and need to parse it at start of every method. Is it possible to handle it somehow?
public class AppServiceController : Controller
{
[HttpPost]
public ApiMethodResponse TestPost(string p1, int p2, double p3)
{
// Use p1, p2, p3 parsed from post body json here
}
}
POST body Json sample:
{
"p1": "test value",
"p2": "2",
"p3": "2.3"
}
UPD
Thanks for the answers, it is interesting info for me, but I have many methdos in my controller and they have different signatures, so I need to create model for every method. In DrJay method it looks even complex becuase I additionaly need to determine model by json structure.
So I return to my question: is it possible to parse JSON and get it’s values in method params (like in GET)?
3
Answers
Thanks, guys, for your answers, they get me a clue. So, I achive what I need.
Test JSON:
Yes, you can do this by creating a custom model binder in ASP.NET Core.
This custom model binder will automatically parse the JSON body and bind the parameters to the action method:
Create a custom model binder:
Csharp
Register the custom model binder in your startup.cs file:
Csharp
Use the custom model binder in your action method:
Csharp
Obviously replace YourModelClass with the class that represents the structure of your JSON input data.
Try something like the below.
‘PostData’ represents the structure of the JSON object. Adding the [FromBody] attribute tells it to automatically bind the JSON data, in the request body, to the PostData object. You can then access the properties of the PostData object (postData.p1, postData.p2, postData.p3) within your method.