简体   繁体   中英

.net core controllers - Add [FromBody] attribute to method or not?

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM