Search code examples
c#.netwebapi.net-7.0

.NET 7 Web Api Deserialize Request Body


I have an Article entity:

public class Article
{
    public string Title { get; private set; }
    public string Description { get; private set; }
    public string Body { get; private set; }
}

To create it through a HTTP POST request, I have to respect this JSON contract:

{
    "article": {
        "body": "body goes here",
        "description": "description goes here",
        "title": "title goes here"
    }
}

Well, how can I do this?

I'm trying the following, but it doesn't work:

public class ArticleRequest
{
    public Article? Article;
}
[HttpPost]
public IActionResult Create([FromBody] ArticleRequest request)
{
    return Ok(request);
}

I get no errors, just an empty object as response:

enter image description here

I have tried custom JSON deserialization but also got nothing.


Solution

  • Just change the ArticleRequest class to include a property:

    public class ArticleRequest
    {
        public Article? Article { get; set; }
    }