I am using .NET 5 web api. I have a webhook that posts to my api. However, When I receive the POST in a string it is null. If I create a class, then .Net will parse the JSON for me, but I need a string, not an object. Any advice is greatly appreciated!
Example of JSON POST (application/json; charset=UTF-8):
{
"user_ip": "00.00.00.00",
"date_start": "2022-01-01T14:05:27.546Z",
"user_referrer": "N/A",
"user_os": "Windows (deprecated)",
"id": "000001",
"items": [
{
"id": "1",
"position": 2,
"value": "01/01/2022"
},
{
"id": "0",
"position": 8,
"value": "Smith"
},
{
"id": "1",
"position": 22,
"value": "7843377133"
},
{
"values": [
{
"position": 2,
"value": "Coffee"
},
{
"position": 5,
"value": "Tea"
}
],
"id": "14",
"position": 7
},
{
"id": "15",
"position": 8,
"value": "This is a test for API"
}
],
"user_device": "Desktop"
}
Endpoint - val
is null when type string:
[ApiController]
[Route("api/webhooks/[controller]")]
public class FormController : BaseApiController
{
[HttpPost("Form")]
public async Task<ActionResult> Form([FromBody] string val)
{
FormDataModel FS = new FormDataModel(){
ResultJsonString = val
};
return Ok(new {Data = FS});
}
CodePudding user response:
you can only use JObject input parameter for example and convert it to json using ToString()
public async Task<ActionResult> Form([FromBody] JObject val)
{
ResultJsonString = val.ToString();
.... another code
}
another way is to serialize twice before POST to API, in this case you can get a string as val, but it is very bad coding style.
CodePudding user response:
You would need a template object to deserialize the json, and then you can access the string as a member of the object created. i. e.
[ApiController]
[Route("api/webhooks/[controller]")]
public class FormController : BaseApiController
{
[HttpPost("Form")]
public async Task<ActionResult> Form([FromBody] CustomObject val)
{
FormDataModel FS = new FormDataModel(){
ResultJsonString = val.items[0].value
//or whatever path it is to the string you're interested in
};
return Ok(new {Data = FS});
}