Previous Implementing JWT Authentication in ASP.NET Core Synchronous and Asynchronous in .NET Core Next

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
Back to Index
Previous Implementing JWT Authentication in ASP.NET Core Synchronous and Asynchronous in .NET Core Next
*