Search code examples
.net.net-core

.Net Core How to handle Post with object not wrapped


I'm trying to receive a webhook from a third-party site, and the JSON Object is not wrapped - meaning, this object is the root object:

{
   "Name": "Dan",
   "FavoriteSite": "Stack Overflow"
}

My Controller looks like this:

[HttpPost]
public IActionResult Post([FromBody] MyObject o)
{
    System.Console.WriteLine("Woop");
    return Ok();
}

However, all values are NULL when I set a breakpoint and view in the debugger. I believe it's because there's no root type on the JSON, but I could be wrong. Is there a way to make this work, or am I doing something really basic wrong?


Solution

  • If the json-structure is unknown, one option is to map the request body to a json object using the JsonElement

    [HttpPost]
    public IActionResult Post([FromBody] JsonElement json)