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

Custom Model Binders in ASP.NET Core

Custom Model Binders in ASP.NET Core
December 6, 2019 4 min read BEN ABT
.NET ASP.NET Core

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

What are Model Binders?

ModelBinders are required in ASP.NET Core to pass parameters from HTTP requests into a controller action method.

For example, they ensure that an ID from a URL is available as a parameter in the method, taking into account the respective parameter type.

C#
1// users/1
2public IActionResult GetById(int id) ..

Why custom model binders?

Own ModelBinders can be used very practically, e.g. to avoid repetitive code.

For example, very often the current user is needed in a web application; but maybe not every property of the user is needed, but only the id.

ASP.NET Core has ModelBinders for the types existing in .NET on board by default; you have to register your own. All standard ModelBinders can be overwritten or deactivated, but this is only necessary in special cases.

Sample

As an example I use a class that should represent the current id of the user. The Id comes from a default id-claim of the current ClaimIdentity.

Normally this would require the following code in each action:

C#
 1
 2public IActionResult MyAction()
 3{
 4    int? userId;
 5
 6    var user = this.User;
 7    var claims = user.Claims;
 8    var idClaim = claims.SingleOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier);
 9
10    if(idClaim != null)
11    {
12        if (int.TryParse(idClaim.Value, out int claimIdValue)
13        {
14            userId = claimIdValue;
15        }
16    }
17
18    // you can use userId here
19    // ...
20}
21
22## Binder Class
23
24In order for a ModelBinder to become active at all, we need a separate class for it.
25Thanks to the type, ASP.NET Core can later recognize which ModelBinder must be used.
26
27Since our user id is always an integer, I gave the model some operators to make it easier to use against methods with int parameters.
28
29```csharp
30    public class PortalUserId
31    {
32        public PortalUserId(int value)
33        {
34            Value = value;
35        }
36
37        public int Value { get; }
38
39        public static implicit operator PortalUserId(int value)
40        {
41            return new PortalUserId(value);
42        }
43
44        public static implicit operator int?(PortalUserId userId)
45        {
46            return userId?.Value;
47        }
48
49        public static implicit operator int(PortalUserId userId)
50        {
51            return userId.Value;
52        }
53    }

The goal is to have this class available at every necessary action as a parameter to avoid the constantly repeating code.

C#
1public IActionResult MyAction(PortalUserId userId)
2{
3    // you can use userId here
4    // ...
5}

The Model Binder

The ModelBinder ensures that ASP.NET knows what to do with each type in the action’s parameter list - and what data and sources to use to create the object.

At this point, in-memory information (like here from the HTTP context) can be used as a source, just like databases or files.

However, it is recommended that this is done with a high performance.

I like to use this to centralize recurring queries, also with MediatR and asynchronous operations / notifications.

C#
 1public class PortalUserIdBinder : IModelBinder
 2{
 3    public Task BindModelAsync(ModelBindingContext bindingContext)
 4    {
 5        if (bindingContext == null)
 6        {
 7            throw new ArgumentNullException(nameof(bindingContext));
 8        }
 9
10        PortalUserId portalUserId = null;
11
12        int? userId = null;
13
14        // find user and the claims
15        var user = bindingContext.ActionContext.HttpContext.User;
16        var claims = user.Claims;
17        var idClaim = claims.SingleOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier);
18
19        // find claim and read value
20        if (idClaim != null)
21        {
22            if (int.TryParse(idClaim.Value, out int claimIdValue)
23            {
24                userId = claimIdValue;
25            }
26        }
27
28        // create object if id is valid
29        if (userId.HasValue)
30        {
31            portalUserId = PortalUserId.Create(userId.Value);
32        }
33
34        // if user id was found, the filled object is passed
35        //      if userId was not found, null will be passed to the actions
36        bindingContext.Result = ModelBindingResult.Success(portalUserId);
37        return Task.CompletedTask;
38    }
39}

Register the ModelBinder

For ASP.NET Core to even know the binder, it must be registered through a binder provider.
This is where the mapping between binder and type takes place.

If you should have several binders, because you want to save a lot of code in many actions, then you can easily register several binders here.

C#
 1    public class PortlModelBinderProvider : IModelBinderProvider
 2    {
 3        public IModelBinder GetBinder(ModelBinderProviderContext context)
 4        {
 5            if (context is null) throw new ArgumentNullException(nameof(context));
 6
 7            // our binders here
 8            if (context.Metadata.ModelType == typeof(PortalUserId))
 9            {
10                return new BinderTypeModelBinder(typeof(PortalUserIdBinder));
11            }
12
13            // your maybe have more binders?
14            // ....
15
16            // this provider does not provide any binder for given type
17            //   so we return null
18            return null;
19        }
20    }

Then the BinderProvider must also be made known.

C#
 1public void ConfigureServices(IServiceCollection services)
 2{
 3    // ....
 4
 5    services.AddControllersWithViews(o =>
 6    {
 7        // adds custom binder at first place
 8        o.ModelBinderProviders.Insert(0, new PortlModelBinderProvider());
 9
10    }).AddRazorRuntimeCompilation();
11
12    // ....
13}

Ready is our binder structure, which now saves us a lot of code in our actions :-)

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