Understanding [FromForm], [FromBody], [FromQuery], [FromRoute], and [FromHeader] in ASP.NET Core
When building APIs in ASP.NET Core, understanding how to bind incoming data to your action parameters is crucial. So in this article we will see the difference between all these attributes.
[FromForm]
Use [FromForm] when you want to bind data submitted as part of a form, typically via `multipart/form-data` or `application/x-www-form-urlencoded`. This is often used when handling form submissions in web applications.
public IActionResult SubmitData([FromForm] MyFormModel model)Example: Uploading a file with additional form data.
[FromBody]
[FromBody] is used to bind data from the body of the request, typically in JSON or XML format. This is common in API endpoints that accept complex objects or raw data.
public IActionResult CreateItem([FromBody] MyItemModel item)Example: Posting JSON data to create a new resource.
[FromQuery]
[FromQuery] binds data from query string parameters in the URL. This is useful for filtering, sorting, or searching operations where data is passed via the query string.
public IActionResult GetItems([FromQuery] string filter)Example: `GET /items?filter=active`
[FromRoute]
Use [FromRoute] when you want to bind data directly from the route parameters in the URL. This is often used for identifying resources.
public IActionResult GetItem([FromRoute] int id)Example: `GET /items/123` where `123` is the ID of the item.
[FromHeader]
[FromHeader] allows you to bind data from HTTP headers. This is useful for scenarios where you need to pass metadata, such as authentication tokens or custom headers.
public IActionResult GetData([FromHeader(Name = "X-Custom-Header")] string headerValue)Example: Passing an API key via a custom header like `X-API-Key`.
Why Does This Matter? 🤔
Choosing the right attribute helps make your API clear, predictable, and easy to use. It ensures that your application correctly interprets where data is coming from, making your code more maintainable and reducing the risk of bugs.


