Posting complex type in ASP.NET Core

Viewed 12420

I am experiencing an issue while developing a restful webapi with .Net Core, I can't consume a HTTP POST method that inserts a complex type object without specifying the parameter as "FromBody". Accordingly to the documentation from Microsoft...

Parameter Binding in ASP.NET Web API

When using complex types on a HTTP POST I don't have to specify a [FromBody] data annotation, it should just work, but when I try to consume the method from the webapi...

// POST api/checker/
[HttpPost]
public int Insert(Entity e)
{
    Console.WriteLine($"Entity: {e.ID} - {e.Name}");
}

where entity has an id and a name, with this client method ...

string json = JsonConvert.SerializeObject(entity);        
HttpClient client = new HttpClient();            
HttpResponseMessage message         = await client.PostAsync(
        "http://localhost:5000/api/checker", 
        new StringContent(json, Encoding.UTF8, "application/json"));

The object reaches the webapi with the values 0 (ID) and null (name), unless when the webapi method signature uses the [FromBody] annotation. Am I missing something here? I've already done a research and couldn't figure this out.

Update:

This is my entity class:

public class Entity
{
    public int ID { get; set; }
    public bool IsDeleted { get; set; }
    public string Name { get; set; }
}

This is the serialized json using Newtonsoft's JSON.NET:

{"ID":99,"IsDeleted":false,"Name":"TestChecker"}

This is the output from the insert web api method:

Entity: 0
3 Answers
Related