Asman Umbetov
Asman Umbetov

Reputation: 122

ASP.NET HttpPost method. can't receive data properly

There's the project, that has Node class declared

public class Node
{
    public string id { get; set; }
    public int group { get; set; }

    public Node( string id, int group)
    {
        this.id = id;
        this.group = group;
    }

    public Node()
    {
    }
}

And method, that has to receive this object and do stuff with it

[HttpPost]
public IActionResult Create(Node node)
{
    //does stuff here
    return NoContent();
}

One thing I can't understand is how my JSON object has to look like to be correctly deserialized in this method. I mean I tried to send JSON that looked like this: { "id": "TEST", "group": 1} but thing received object with id = null, group = 0. I don't get it, what do I do wrong?

Upvotes: 2

Views: 562

Answers (2)

Ammar Iqbal
Ammar Iqbal

Reputation: 51

If you are ever struggling with deserializing a body, try and do it manually to see if you are actually sending it correctly.

[HttpPost]
public void Post()
{
    string body = Request.Content.ReadAsStringAsync().Result;
}

Upvotes: 1

Alex
Alex

Reputation: 38509

By default, the action method model binding in ASP.net is looking for application/x-www-url-formencoded encoded form values.

You are POSTing JSON in the body of your request, so you need to use the [FromBody] attribute.

[HttpPost]
public IActionResult Create([FromBody] Node node)
{
    //does stuff here
    return NoContent();
}

Upvotes: 1

Related Questions