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
There was a split/change in asp.net core from previous versions as MVC & Web Api Controllers merged together.
The default behavior in asp.net core, for POST requests, it that it will look for the data in request body using form data (x-www-form-urlencoded). You have to be explicit if you want to find appliction/json from body json.
This link might help you with details: https://andrewlock.net/model-binding-json-posts-in-asp-net-core/
I think you'll find that you need FromBody in .Net Core. See Create a Web API with ASP.NET Core... See also : Model Binding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With