Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't my post JSON object getting serialized?

Why isn't my POST JSON object getting serialized? I'm using Web API 2.0. My controller route looks like this:

[HttpPost]
[Route]
public async Task<IHttpActionResult> AddUserAsync([FromBody] User user)
{
    //do some stuff
}

My User object looks like this:

public class User
{
    Guid Id { get; set; }

    string Name { get; set; }
}

When I pass the following JSON object the Id and Name props get serialized with null values:

{
    "Id": "895C4492-B751-462C-9738-C6CB4E94E21F",
    "Name": "Joe System"
}

Do I need to decorate User with [DataContract] or something like that?

How to manage this in Web API 2?

like image 377
user9393635 Avatar asked May 10 '26 02:05

user9393635


1 Answers

Your properties are not public. You need to make them public

public class User {
    public Guid Id { get; set; }    
    public string Name { get; set; }
}

The model binder inspects the intended object type and populates public properties.

Reference Parameter Binding in ASP.NET Web API

like image 170
Nkosi Avatar answered May 12 '26 18:05

Nkosi