Fals
Fals

Reputation: 6839

ASP.NET Web API body value restriction

I'm studying ASP.NET Web API, but somewhere in the explanation about complex types that comes from the request body the author confuses me:

PROFESSIONAL ASP.NET MVC 4: Chapter 11 - ASP.NET Web API

"[..] complex types (everything else) are taken from the body. There is an additional restriction as well: Only a single value can come from the body, and that value must represent the entirety of the body. [...]"

Brad Wilson

What does his mean with this "single value can come from the body"? The API formatters can parse only a single type of object from the body? Could you illustrate this by example?

Upvotes: 4

Views: 328

Answers (2)

Only a single value can come from the body

Assume you have a request body like this.

{"Id":12345, "FirstName":"John", "LastName":"West"}

You want this JSON to be bound to a parameter of type like this.

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

The action method can be like void Post(Employee emp). And it cannot be like this - void Post(Employee john, Employee duplicateJohn). Only a single value can come from the body.

and that value must represent the entirety of the body

Assume you have the same request body like this.

{"Id":12345, "FirstName":"John", "LastName":"West"}

And you have two DTOs like this.

public class Identifier
{
    public int Id { get; set; }
}

public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

You cannot have an action method like void Post(Identifier id, Name name) and expect the body to be bound partially to both the parameters. Body in its entirety must be bound to only one value. So, having a class like

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and binding the request body in its entirety to one value like void Post(Employee emp) is only allowed.

Upvotes: 4

Teoman Soygul
Teoman Soygul

Reputation: 25732

This basically means that you cannot have multipart body that describes more than one complex type. Say if you have a User type, the entire body must describe that User type and not User + ShoppingChart types.

Valid body for User type:

{
   "id" : "1",
   "username" : "someuser"
}

Invalid body for User type:

{
   "user" : {
      "id" : "1",
      "username" : "someuser"
   },

   "shoppingCart" : {
      "cartId" : "1",
      "items" : "5"
   }
}

Of course, you can create a new complex type like UserAndShoppingCart (which uses user and shopping cart classes as properties) and now the invalid body will be valid and deserializable for this new type.

Upvotes: 1

Related Questions