Introduction
In ASP.NET Core Web API, model binding is the process of mapping incoming HTTP request data (such as query string, route values, or request body) to action method parameters. By default, ASP.NET Core provides powerful built-in model binding that works well for most scenarios.
However, in real-world applications, there are situations where default model binding is not enough. For example, you may need to transform input data, combine multiple inputs, or parse complex formats. In such cases, a custom model binder becomes very useful.
This article explains how to implement a custom model binder in ASP.NET Core step by step, with clear explanations, examples, and best practices.
What is Model Binding in ASP.NET Core?
Model binding is a mechanism that automatically maps data from an HTTP request to parameters in your controller action.
For example:
[HttpGet]
public IActionResult GetUser(int id)
{
return Ok(id);
}
Code Explanation
ASP.NET Core automatically reads the
idvalue from the query string or route.It converts the value into an integer.
The converted value is passed to the action method.
This automatic process is called model binding.
Why Do We Need a Custom Model Binder?
In practical ASP.NET Core Web API development, you may face scenarios where default model binding does not meet your requirements.
Common Scenarios
Parsing custom formatted data (e.g., comma-separated values)
Combining multiple request values into a single model
Handling special data types
Applying custom validation or transformation logic
A custom model binder allows you to control how data is read, processed, and assigned to your model.
Step 1: Create a Custom Model
Let’s create a simple model that represents a date range.
public class DateRange
{
public DateTime From { get; set; }
public DateTime To { get; set; }
}
Explanation
This model will hold two values: start date and end date.
Step 2: Create a Custom Model Binder
Now, create a custom model binder by implementing IModelBinder.
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
public class DateRangeModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).FirstValue;
if (string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
var dates = value.Split(',');
if (dates.Length != 2)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Invalid date range format");
return Task.CompletedTask;
}
var model = new DateRange
{
From = DateTime.Parse(dates[0]),
To = DateTime.Parse(dates[1])
};
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}
Join the conversation! Your thoughts help the community grow.