[FromForm], [FromQuery],[FromBody],[FromHeader],[FromQuery],[FromRoute]

Viewed 12489

I am slowly learning the .Net Core. I caught my head thinking when to use [FromForm], [FromQuery],[FromBody],[FromHeader],[FromRoute] [FromService]. Could anyone please help me in understanding them because I am confused when to use which directive.

2 Answers

In simple words,

[FromQuery] is to get values from the query string
[FromRoute] is to get values from route data
[FromForm] is to get values from posted form fields
[FromBody] is to get values from the request body
[FromHeader] is to get values from HTTP headers
[FromService] will have value injected by the DI (Dependency Injection) resolver

These attributes tell the MVC model binder from where to read the values from when the controller action is called or invoked.

For more information on model binding and about the usage of the above attributes please refer the following MSDN link

MSDN Reference -> Model Binding in ASP.NET Core

Here you can read a quite comprehensive article: https://www.dotnetcurry.com/aspnet/1390/aspnet-core-web-api-attributes

But to be short: you can add these attributes to Web API controller methods (actions). More precisely to their parameters. For example:

public Task<Order> Get([FromQuery(Name = "identifier")] int id, [FromServices] IOrderService orderService)

They are telling the framework where to inject values from when the action is called. Most of them will use some part of the http request itself, but parameters decorated with [FromService] will have value injected by the DI resolver.

Related