MSDN Documentation

.NET Web API Binding

Web API Binding

In .NET Web API, binding refers to the process of taking incoming HTTP request data (such as route values, query strings, form data, and request bodies) and mapping it to the parameters of your controller actions.

This mechanism simplifies development by automatically handling the deserialization and population of your action parameters, whether they are simple types, complex objects, or even collections.

Core Concepts

Understanding binding involves two key components:

Model Binding

Model binding is the heart of this process. When a request arrives, Web API inspects the incoming data and tries to bind it to your controller action parameters.

Providers

Web API has built-in providers for common data sources:

Sources

The order in which Web API looks for values can be configured, but by default, it prioritizes:

  1. Route values
  2. Query string values
  3. Form values
  4. Request body (for complex types)

Custom Model Binders

For scenarios not covered by the default binders, you can create your own custom model binder by implementing the IModelBinder interface. This gives you complete control over how data is converted.

Example: Creating a Custom Model Binder


public class MyCustomBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(MyCustomType))
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue("myCustomProperty");
            if (valueProviderResult == default(ValueProviderResult))
            {
                return Task.CompletedTask;
            }

            var value = valueProviderResult.FirstValue;
            // Perform custom conversion logic here
            var customObject = new MyCustomType { /* ... */ };
            bindingContext.Result = ModelBindingResult.Success(customObject);
            return Task.CompletedTask;
        }
        return Task.CompletedTask;
    }
}
                

Value Providers

Value providers are the source from which model binders extract data. Web API comes with several built-in value providers.

Route Values

Values defined in your route templates. For example, in a route like /api/products/{id}, the id is a route value.

Query String

Parameters added to the URL, e.g., /api/products?category=electronics&sort=price.

Form Data

Data submitted via HTML forms, often in POST requests. This can include application/x-www-form-urlencoded and multipart/form-data.

Headers

Information passed in HTTP headers, such as custom headers or authentication tokens.

Custom Providers

You can also implement custom value providers if you need to extract data from unusual sources.

Binding Attributes

Attributes can be used to explicitly tell Web API where to look for a parameter's value, overriding default behavior. Common attributes include:

Example: Using Binding Attributes


[HttpGet("{id}")]
public IActionResult GetProduct([FromRoute] int id, [FromQuery] string detailLevel)
{
    // ...
}

[HttpPost]
public IActionResult CreateOrder([FromBody] OrderModel order)
{
    // ...
}
                

Advanced Topics

Effective use of Web API's binding system is crucial for creating robust and maintainable web services.