5

Is there a function of [FromBody] attribute? I mean, when I use it for example:

public async Task SetUser([FromBody]User user)

and when I use:

public async Task SetUser(User user)

The server get the same object without problems, so, it's necessary set it, or I can remove it without worries?

Grettings!

L Leon
  • 143
  • 1
  • 8
  • Check this link for more details : http://stackoverflow.com/questions/24625303/why-do-we-have-to-specify-frombody-and-fromuri-in-asp-net-web-api – Vijai Aug 26 '16 at 22:11
  • 1
    Possible duplicate of [Why do we have to specify FromBody and FromUri?](https://stackoverflow.com/questions/24625303/why-do-we-have-to-specify-frombody-and-fromuri) – Bartho Bernsmann Mar 17 '18 at 21:55

2 Answers2

10

User is a complex type, so by default the server will try to resolve it from the request body. If you had a simple type -- e.g.

public async Task SetUser(string userId)

the server would try to resolve the value via URL binding. You can override that behaviour by specifying

public async Task SetUser([FromBody] string userId)

I usually leave [FromBody] in the signature simply for the sake of readability.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74
7

There are two ways parameters can be passed to the server - via URI, or as part of the request body.

When data are passed in URI, they become query string - e.g. http://server.com/something?userId=5. This will be handled by the action method with int userId argument.

When data are passed in request body, then you cannot see them in the URI - it would be http://server.com/something, for example. Parameters are then passed as name-value pairs inside the request body.

However, in order to pass anything through body, there must be the body, and GET request normally doesn't have request body (it can have it, technically, but I'm not sure if it's used to pass parameters to GET action methods). You would usually expect arguments to be adorned with the FromBody attribute in POST action methods. Likewise, you would usually expect GET actions to receive arguments through URI, which is more in line with the purpose of the GET method.

You can specify either FromUri or FromBody to control behavior. There is also BindModel attribute which lets you define custom binding.

Zoran Horvat
  • 10,924
  • 3
  • 31
  • 43