Reputation: 97
I have a method as described below which get user as parameter. To send the user parameter values, I am using postman request/response tool. My question is, if the request already have user parameter in body request (see at the postman print screen ) why do I need to directly specify [FromBody] in action controller? When this attribute removed, parameter send with null values.
Thanks
[HttpPost("register")]
public IActionResult Register([FromBody]User user)
{
//.. code here
}
public class User
{
public string Name { get; set; }
public string Password { get; set; }
}
Upvotes: 7
Views: 71618
Reputation: 29
the attribute [FromBody] ensures the API reads the JSON payload in the HTTP Request body. For more info, read
Upvotes: -6
Reputation: 29976
For Model Binding in ASP.NET Core, MVC and Web APi uses the same model binding pattern.
There are default model bindings like Form Values, Route values and Query Strings. If these bindings fails, it will not throw an error, and return null.
If you do not want to add [FromBody]
, you could try Form Values binding and send request from Postman like below:
[FromBody]
will override default data source and specify the model binder's data source from the request body.
You could refer Model Binding in ASP.NET Core for detail information
Upvotes: 5
Reputation: 988
The [FromBody]
directive tells the Register action to look for the User parameter in the Body of the request, rather than somewhere else, like from the URL. So, removing that confuses your method, and that's why you see null values as it's not sure where to look for the User
parameters.
See: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api for more information/learning.
Upvotes: 6