-1

I'm working on small web app, and when it comes about controllers / endpoints, I saw on many please that some people are adding [FromBody] attribute in method parameters and some not.

I can't figure out what is the point ?

Here is the example:

public async Task<ActionResult> UploadImages([FromBody] ProductImagesRequestDto productImagesRequestDto)

vs 

public async Task<ActionResult> UploadImages(ProductImagesRequestDto productImagesRequestDto)

Is this endpoint the same?

What is difference in this two methods definitions if there are any ... ?

Thanks everyone

Cheers

Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102
  • You can refer to [Binding source parameter inference](https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-5.0#binding-source-parameter-inference) in ApiController. – mj1313 Nov 17 '20 at 08:34

2 Answers2

2

No they're not. When you provide the binder then you are saying to model binder to explicitly where to look and what to look for:

  • FromRoute binds values from route data
  • FromBody binds values from the request body
  • FromQuery binds values from the query string
  • FromForm binds values from form fields
  • FromHeader binds values from headers

If you don't provide any binder, you are at the hands of the model binder's default behaviour. It will search in default available binders to match the action parameters. If it can't match any there'll be model state errors or content type errors, if when it is been said to use FromBody binder and, say, the post data has been sent with x-www-form-urlencoded.

Hasan Manzak
  • 663
  • 6
  • 14
0

Parameters may be passed through URI or as part of a request body.

Specifying the FromBody attribute simply ensures that the parameter is passed as part of the request body instead of in the URI.

Depending on the type of parameter being passed (and how sensitive that data is), it may be considered best practice to have all parameters in the request body so that it is not visible in the URI

btamsevi
  • 1
  • 2
  • 1
    thanks for reply but I'm wondering in this specific example what is difference ? – Roxy'Pro Nov 16 '20 at 23:28
  • If your controller has [ApiController] attribute there is no difference at all. – Neistow Nov 16 '20 at 23:32
  • @Neistow It has, but why is that ? How come ? – Roxy'Pro Nov 16 '20 at 23:33
  • Adding that attribute marks a controller as API controller enabling such features like auto model validation and parameters interference which means that asp net core will try to guess and bind model from available sources. Also afaik default bind source if from body – Neistow Nov 16 '20 at 23:36
  • @Neistow no, default binder is not FromBody. Actually there's no single default binder. There's a `Provider List`, and all binders are available. Model binder just searches for the best match, if any spesific binder is not provided. – Hasan Manzak Nov 16 '20 at 23:52