In ASP.NET Core Web API or MVC, Model Binding and Model Validation work together to handle incoming HTTP requests cleanly and securely.
What is Model Binding?
Model Binding is the process by which ASP.NET Core automatically maps incoming HTTP request data (from the query string, form data, route, headers, or body) to C# parameters or objects.
Sources of Model Binding:
Source | Attribute Used (Optional) | Example |
---|---|---|
Query string | [FromQuery] | /api/products?name=TV |
Route | [FromRoute] | /api/products/5 |
Body (JSON) | [FromBody] | POST with JSON payload |
Form data | [FromForm] | Used in HTML form uploads |
Header | [FromHeader] | Custom header values |
Here's a comprehensive example demonstrating all types of Model Binding in ASP.NET Core Web API — using [FromRoute], [FromQuery], [FromBody], [FromHeader], and [FromForm].
ASP.NET Core Model Binding Example:
Step 1: Model Class:
public class ProductDto { public string Name { get; set; } public decimal Price { get; set; } }
[ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { // 1. FromRoute Example // URL: /api/products/5 [HttpGet("{id}")] public IActionResult GetById([FromRoute] int id) { return Ok($"FromRoute: Product ID = {id}"); } // 2. FromQuery Example // URL: /api/products/filter?name=Laptop&price=1000 [HttpGet("filter")] public IActionResult Filter([FromQuery] string name, [FromQuery] decimal price) { return Ok($"FromQuery: Name = {name}, Price = {price}"); } // 3. FromBody Example // POST JSON: { "name": "Tablet", "price": 500 } [HttpPost] public IActionResult Create([FromBody] ProductDto product) { return Ok($"FromBody: Name = {product.Name}, Price = {product.Price}"); } // 4. FromHeader Example // Headers: X-User-Id: 101 [HttpGet("secure")] public IActionResult Secure([FromHeader(Name = "X-User-Id")] int userId) { return Ok($"FromHeader: User ID = {userId}"); } // 5. FromForm Example // Form Data: name=Phone, price=300 [HttpPost("upload")] public IActionResult Upload([FromForm] ProductDto product) { return Ok($"FromForm: Name = {product.Name}, Price = {product.Price}"); } }
What is Model Validation?
Model Validation ensures that the data received from the client meets the specified rules and constraints. It runs after model binding and before executing the controller action.
Common Validation Attributes:
- [Required]: Field must not be null/empty
- [StringLength]: Limits string length
- [Range]: Specifies a numeric range
- [EmailAddress]: Validates email format
- [RegularExpression]: Pattern-based validation
Example of Model Validation:
public class Product { public int Id { get; set; } [Required] [StringLength(100)] public string Name { get; set; } [Range(1, 10000)] public decimal Price { get; set; } } [HttpPost] public IActionResult CreateProduct([FromBody] Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); // Returns validation errors } return Ok(product); }
Flow: Model Binding + Validation
Client Request (JSON or Query) ↓ Model Binding (Maps request to C# model) ↓ Model Validation (Validates using attributes) ↓ Action Method Executes (if valid)
No comments:
Post a Comment