.net.net-core

How to handle Post with an object not wrapped in .NET Core


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 isn't any root type in 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)