Model Binding in .NET Core
|
|
π§© What Is Model Binding?
Model Binding is the process of automatically mapping HTTP request data (from query strings, forms, route data, headers, or body) to action method parameters or model properties.
β
Benefits
- Converts raw HTTP data into strongly typed .NET objects
- Eliminates manual parsing and casting
- Supports simple and complex types (e.g.,
int, string, Student, Order)
π Example
[HttpPost]
public IActionResult Register(UserModel model)
{
// model.Username and model.Password are automatically bound
return Ok(model);
}
π¦ Common Binding Sources
| Attribute |
Source |
Example Usage |
[FromQuery] |
Query string |
/api/user?name=John |
[FromRoute] |
Route data |
/api/user/123 |
[FromForm] |
Form fields |
<form method="post">...</form> |
[FromBody] |
Request body |
JSON payload in POST/PUT |
[FromHeader] |
HTTP headers |
Custom headers like X-User-Id |
π§ͺ What Is Model Validation?
Model Validation checks whether bound data conforms to business rules or data annotations. It runs after model binding and stores results in ModelState.
π Example with Data Annotations
public class UserModel
{
[Required]
[StringLength(100)]
public string Username { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
π Controller Validation Logic
[HttpPost]
public IActionResult Register(UserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Proceed with valid model
return Ok("Registration successful");
}
If you use [ApiController], ASP.NET Core automatically returns a 400 Bad Request when ModelState is invalidβno need to check manually.
π§ Best Practices
- β
Use
[ApiController] for automatic validation in Web APIs
- π§Ό Keep models clean and focused on validation logic
- π Use
TryValidateModel() for manual re-validation
- π§ͺ Use
ModelState.ClearValidationState() before re-validating modified models
- π Prefer
[FromBody] for complex types in POST/PUT