Model Binding in Web API
Learn how model binding works in ASP.NET Core Web API and how data from HTTP requests is automatically mapped to parameters and models in your application.
Part 1: What Is Model Binding?
Model binding is the process of automatically converting incoming HTTP request data into .NET objects that your application can use.
Instead of manually reading values from the request, ASP.NET Core handles the mapping for you.
Part 2: Sources of Data
Model binding can extract data from different parts of a request:
- Route values (URL segments)
- Query strings
- Form data
- Request body (JSON)
- Headers
This makes it flexible and powerful for handling various types of input.
Part 3: Simple Parameter Binding
Model binding can automatically map route parameters to method parameters.
public string GetStudent(int id)
{
return "Student " + id;
}
The id value from the URL is automatically passed into the method.
Part 4: Binding from Query String
Query string values can also be bound automatically.
public string Search(string name)
{
return "Searching for " + name;
}
Example URL: /api/students?name=Alice
Part 5: Binding Complex Objects
Model binding can map JSON request data to complex objects.
{
public string Name { get; set; }
public int Age { get; set; }
}
[HttpPost]
public IActionResult Create(Student student)
{
return Ok(student);
}
The JSON request body is automatically converted into a Student object.
Part 6: Using Binding Attributes
You can control where data comes from using attributes:
[FromRoute][FromQuery][FromBody][FromForm]
This explicitly tells ASP.NET Core where to get the data.
Part 7: Model Binding in the Student Project
In your Student API, model binding is used extensively:
- Receiving student data from forms or JSON
- Handling route parameters like student ID
- Processing query filters
- Mapping request data into objects
This simplifies code and reduces manual data handling.
Part 8: Best Practices
- Use clear and simple models
- Validate input data properly
- Use binding attributes when needed
- Avoid overly complex models
- Handle invalid input gracefully
Good model binding practices improve reliability and maintainability.
Summary
Model binding is a powerful feature in ASP.NET Core Web API that automatically maps request data to method parameters and objects. It simplifies development and helps you build clean, efficient, and scalable APIs.