Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting complex type in ASP.NET Core

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
like image 561
dandev486 Avatar asked Jul 28 '17 14:07

dandev486


2 Answers

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/

like image 50
dee zg Avatar answered Oct 07 '22 22:10

dee zg


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.

like image 35
Richard Hernandez Avatar answered Oct 07 '22 22:10

Richard Hernandez