Reputation: 6803
I am using web-api 2 and postman rest client to test.
I have a method definition which looks like this:
[Route("api/bob/user")]
[HttpPut]
public IHttpActionResult UpdateUser(User user)
The user object looks like this:
public class User : IUser
{
public string Firstname { get; set; }
public string Lastname { get; set; }
}
public interface IUser
{
string Firstname { get; set; }
string Lastname { get; set; }
}
In postman i've set a put request and set the content type to JSON(application/json) I have specified the following in the body as raw:
{
"user": {"Firstname":"Bob","Lastname":"Smith"}
}
When I send the request the object type is detected but none of the properties are populated (they are all null), leading me to believe the de-serialisation is failing.
If I change the method signature to object I get the json string and can deserialise it to a user object. I'd much prefer strong typing if possible.
my webapiconfig looks like this:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
new MediaTypeHeaderValue("text/html"));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{action}",
defaults: new {id = RouteParameter.Optional});
I also add a screenshot of the test client:
Upvotes: 1
Views: 93
Reputation: 15003
You should not put the user
property before. Your JSON should look like:
{
"Firstname": "Bob",
"Lastname": "Smith"
}
In order for the model binder to bind to the model.
If you wish to go with your current JSON, your User
model should look like
public class User {
public User User { get; set; }
}
Also make sure you use application/json
as the content type.
Upvotes: 5