Difference Between [FromBody] and [FromQuery] in Web API
📌 [FromBody] vs [FromQuery] in ASP.NET Core Web API: What's the Difference?
In ASP.NET Web API and ASP.NET Core, model binding is the process of mapping incoming HTTP request data to action method parameters. Two of the most commonly used model binding attributes are:
- [FromBody] – Binds data from the HTTP request body
- [FromQuery] – Binds data from the URL’s query string
Each serves a specific purpose based on how the client sends the data. Choosing the correct one improves API clarity, usability, and consistency.
📥 [FromBody]
Use [FromBody] when:
- ✅ You expect structured data (like JSON or XML) in the request body
- ✅ You're using POST, PUT, or PATCH to create or update resources
- ⚠️ Only one parameter can be bound from the body per action method.
[HttpPost]
public IActionResult CreateUser([FromBody] UserDto user)
{
return Ok(user);
}
Request Example:
POST /api/users
Content-Type: application/json
{
"name": "John",
"age": 30
}
🔍 [FromQuery]
Use [FromQuery] when:
- ✅ You want to extract simple data types (string, int, bool)
- ✅ You're working with GET endpoints or need to pass filters and parameters
[HttpGet]
public IActionResult Search([FromQuery] string name, [FromQuery] int page = 1)
{
return Ok($"Searching for {name} on page {page}");
}
Request Example:
GET /api/users/search?name=John&page=2
📊 Quick Comparison Table
| Feature | [FromBody] | [FromQuery] |
|---|---|---|
| Source of Data | Request body (JSON, XML) | URL query string |
| Used in Methods | POST, PUT, PATCH | GET, DELETE, sometimes POST |
| Ideal For | Complex objects (DTOs) | Simple filters, paging, sorting |
| Parameter Count | Only one per action | Multiple parameters allowed |
| Format Required | JSON or XML | Key-value string pairs |
💡 Tips
- Use
[FromBody]for structured, posted data like JSON in POST, PUT, or PATCH requests. - Use
[FromQuery]for filters or optional parameters in GET requests.
❓ Common Questions
Q: Can I use [FromBody] and [FromQuery] together?
A: Yes! You can combine them in one action, as long as only one parameter is bound from the body.
[HttpPost]
public IActionResult CreateUser(
[FromBody] UserDto user,
[FromQuery] bool notify = false)
{
// Do something with user and notify
return Ok();
}
Q: What about [FromRoute], [FromHeader], or [FromForm]?
These are other model binding sources:
- [FromRoute] – Extracts values from URL route segments
- [FromHeader] – Gets values from HTTP headers
- [FromForm] – Handles form data (e.g., multipart form uploads)
✅ Summary
- [FromBody] is best for structured payloads in the body (like JSON).
- [FromQuery] is ideal for simple values passed in the query string.
- Choose based on where the data comes from and how the client sends it.
Using these attributes correctly helps you design clean, RESTful, and maintainable APIs.

Comments
Post a Comment