user7372188
user7372188

Reputation:

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

Upvotes: 5

Views: 14034

Answers (3)

tlt
tlt

Reputation: 15211

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/

Upvotes: 6

Richard Hernandez
Richard Hernandez

Reputation: 116

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.

Upvotes: 1

Linh Tuan
Linh Tuan

Reputation: 448

I see you are using action Insert but when you call your api the url is "http://localhost:5000/api/checker" try again with this url "http://localhost:5000/api/checker/insert"? Maybe it will work and you don't need [FromBody].

Upvotes: 0

Related Questions