Web API Model Binding Guide
In Web API, data models can be bound in the following ways:
- Attribute-based model binding: Model binding can be achieved by declaring a property object in the method parameters that corresponds to the request data. For example, the [FromBody] attribute can be used to bind data from the request body to the model object.
public IActionResult Post([FromBody] MyModel model)
{
// 处理模型数据
}
- Parameter-based model binding: Model binding can be achieved by directly declaring parameters in the method that correspond to the request data. For example, the [FromQuery] attribute can be used to bind data from the query string to the parameter.
public IActionResult Get([FromQuery] string name)
{
// 处理查询参数
}
- Route-based model binding: Model binding can be achieved by defining parameters in the route template. For example, a certain part of the route can be bound to a method parameter.
[HttpGet("users/{id}")]
public IActionResult GetUser(int id)
{
// 处理用户ID
}
- Custom model binders: Specific types of binding logic can be handled by implementing custom model binders. For instance, custom binders can be implemented for specific types to extract and convert values of that type from request data.
public class MyModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
// 自定义绑定逻辑
}
}
public IActionResult Get([ModelBinder(typeof(MyModelBinder))] MyModel model)
{
// 处理模型数据
}
Here are some commonly used data model binding methods, you can choose the appropriate one based on your specific needs.