Reputation: 143
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!
Upvotes: 5
Views: 6967
Reputation: 11301
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.
Upvotes: 7
Reputation: 12661
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.
Upvotes: 10