IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Implementing JWT Authentication in ASP.NET Core | Synchronous and Asynchronous in .NET Core | |
Model Binding in .NET Core |
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.
int, string, Student, Order)[HttpPost]
public IActionResult Register(UserModel model)
{
// model.Username and model.Password are automatically bound
return Ok(model);
}
| 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 |
Model Validation checks whether bound data conforms to business rules or data annotations. It runs after model binding and stores results in ModelState.
public class UserModel
{
[Required]
[StringLength(100)]
public string Username { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
[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.
[ApiController] for automatic validation in Web APIsTryValidateModel() for manual re-validationModelState.ClearValidationState() before re-validating modified models[FromBody] for complex types in POST/PUT | Implementing JWT Authentication in ASP.NET Core | Synchronous and Asynchronous in .NET Core | |