Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

Model Binders in ASP.NET Core

Model Binders in ASP.NET Core
December 20, 2018 3 min read BEN ABT
ASP.NET Core

This article was written in 2018. Versions, tools and recommendations may have changed since then. Newer posts are collected under ASP.NET Core.

When ASP.NET Core receives a web request, it routes the request to a specific action - a method that matches the route - of a controller.

Often there is not only the route, there are values too. Like user identifiers, names or complex types in a POST request. The ASP.NET middleware tries to bind the value to the parameter with the specific name - for all parameters.

For example if you have a route with a pattern like /users/{id} and a matching request users/123, the parameter id will have the value 123.

C#
 1[Route("users/{id}", Name = "GetUserById")]
 2public async Task<ActionResult<User>> GetUser(int id)
 3{
 4    User user = await _userRepository.GetAsync(id);
 5    
 6    if ( user is null )
 7    {
 8        return NotFound();
 9    }
10
11    return Ok(user);
12}

If you now have a lot of places where you query the user by id from the database, you can move this code to a custom model binder.

C#
 1public class UserModelBinder : IModelBinder
 2{
 3    private readonly IUserRepository _userRepository;
 4
 5    public UserModelBinder(IUserRepository userRepository) // supports dependency injection
 6    {
 7        _userRepository = userRepository;
 8    }
 9
10    public async Task BindModelAsync(ModelBindingContext bindingContext)
11    {
12        if (bindingContext == null)
13        {
14            throw new ArgumentNullException(nameof(bindingContext));
15        }
16
17        // Specify a default argument name if none is set by ModelBinderAttribute
18        string modelName = bindingContext.ModelName;
19
20        // Try to fetch the value of the argument by name
21        ValueProviderResult valueProviderResult =
22            bindingContext.ValueProvider.GetValue(modelName);
23
24        if (valueProviderResult != ValueProviderResult.None)
25        {
26            bindingContext.ModelState.SetModelValue(modelName,
27                valueProviderResult);
28
29            string value = valueProviderResult.FirstValue;
30
31            // Check if the argument value is null or empty
32            if (!string.IsNullOrEmpty(value))
33            {
34                // check if the value is an int as expected
35                if (!int.TryParse(value, out int id))
36                {
37                    bindingContext.ModelState.TryAddModelError(modelName,
38                        "User Id must be an integer.");
39                }
40                else
41                {
42                    // load the user from the database => repository
43                    User user = await _userRepository.GetAsync(id);
44
45                    // bind the user to the action
46                    bindingContext.Result = ModelBindingResult.Success(result);
47                }
48            }
49        }
50    }
51}

This model binder looks into the requests, tries to get the integer value from the user id parameter id, searched the database for the user and binds the value to the action.

Now we can remove the repository request from our controller:

C#
 1[Route("users/{id}", Name = "GetUserById")]
 2public async Task<ActionResult<User>> GetUser(
 3        [ModelBinder(Name = "id")] User user) // we need the attribut here to "listen" for the parameter "id"
 4{
 5    if ( user is null )
 6    {
 7        return NotFound();
 8    }
 9
10    return Ok(user);
11}

Finally, we still need to register the binder in the middleware. To do this, we first need a provider

C#
 1public class UserModelBinderProvider : IModelBinderProvider
 2{
 3    public IModelBinder GetBinder(ModelBinderProviderContext context)
 4    {
 5        if (context == null)
 6        {
 7            throw new ArgumentNullException(nameof(context));
 8        }
 9
10        if (context.Metadata.ModelType == typeof(User)) // we want to use our custom model binder when action parameter is of type User
11        {
12            return new BinderTypeModelBinder(typeof(UserModelBinder));
13        }
14        else
15        {
16            return null; // ignore all other types
17        }
18    }
19}

Now we can register the binder in the startup class.

C#
1services.AddMvc(options =>
2{ 
3    // Model Binder
4    options.ModelBinderProviders.Insert(0, new UserModelBinderProvider()); // register the binder to be the first one in the pipe
5});

Conclusion

The model binder may seem a bit over the top in this example.

However, if you imagine that you have an application or an API where models or data are needed over and over again, model binders saves you a lot of code - and also makes the actions cleaner.

Related articles

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026 - 12 min read

Problem Details in ASP.NET Core and .NET 11

builder.Services.AddProblemDetails() registers infrastructure. It does not create an error contract. An ASP.NET Core request can fail during …

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026 - 11 min read

Resilience in .NET with Microsoft.Extensions.Resilience

Retries are the most visible resilience strategy and the easiest one to misuse. Repeating a failing call can recover from a short network …

What Matters in ASP.NET Core 11

Sep 14, 2026 - 10 min read

What Matters in ASP.NET Core 11

ASP.NET Core 11 has no single feature that fundamentally changes how web applications are built. That is not a criticism. Mature frameworks …


BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026
Problem Details in ASP.NET Core and .NET 11

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026
Resilience in .NET with Microsoft.Extensions.Resilience

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026
What Matters in ASP.NET Core 11

What Matters in ASP.NET Core 11

Sep 14, 2026

Tags

.NET (192) Csharp (96) ASP.NET Core (48) Azure (41) DevOps (17) Docker (14) Microsoft (14) EF Core (11) Microsoft MVP (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Security (9) Synology (9) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7) Bicep (6)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact