Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FromBody attribute

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

postman request for register action

[HttpPost("register")]
 public IActionResult Register([FromBody]User user)
 {
  //.. code  here 

 }


public class User
{
    public string Name { get; set; }
    public string  Password { get; set; }
}
like image 611
erb 601 Avatar asked Aug 05 '26 12:08

erb 601


2 Answers

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.

like image 107
hmiedema9 Avatar answered Aug 08 '26 02:08

hmiedema9


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:

enter image description here

[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

like image 40
Edward Avatar answered Aug 08 '26 00:08

Edward