ASP.NET Web API Body Cost Limit

I am learning ASP.NET Web API, but somewhere in the explanation about complex types that come 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. additional restriction: only one value can come from the body, and this value must be the fullness of the body. [...]"

Brad Wilson

What does its meaning mean with this "strong" "the only meaning may be from the body"? API formatters can analyze only one type of object from the body? Could you illustrate this with an example?

+4
source share
2 answers

Only one value can come from the body.

Suppose you have a request body like this.

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

You want this JSON to be bound to a type parameter 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 a void Post(Employee emp) . And it can't be like that - void Post(Employee john, Employee duplicateJohn) . Only one value can come out of the body.

, and this value should represent the integrity of the body

Suppose you have the same request object as this one.

{"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 such as void Post(Identifier id, Name name) , and expect the body to be partially bound to both parameters. The whole body should only be tied to the value of one . 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 as a whole to a single value, for example void Post(Employee emp) , is allowed only.

+4
source

This basically means that you cannot have a multi-part body that describes more than one complex type. Say, if you have a User type, the whole body should describe a User type, not User + ShoppingChart .

Valid body for type User :

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

Invalid object for User :

 { "user" : { "id" : "1", "username" : "someuser" }, "shoppingCart" : { "cartId" : "1", "items" : "5" } } 

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

+1
source

Source: https://habr.com/ru/post/1495976/


All Articles