CommandModelBinder 0.0.4

dotnet add package CommandModelBinder --version 0.0.4
                    
NuGet\Install-Package CommandModelBinder -Version 0.0.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CommandModelBinder" Version="0.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CommandModelBinder" Version="0.0.4" />
                    
Directory.Packages.props
<PackageReference Include="CommandModelBinder" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CommandModelBinder --version 0.0.4
                    
#r "nuget: CommandModelBinder, 0.0.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CommandModelBinder@0.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CommandModelBinder&version=0.0.4
                    
Install as a Cake Addin
#tool nuget:?package=CommandModelBinder&version=0.0.4
                    
Install as a Cake Tool

CommandModelBinder for ASP.NET Core

A professional, lightweight library for binding HTTP requests to strongly-typed command objects with built-in authentication, authorization, and serialization support.

๐Ÿš€ Features

  • Type-Safe Command Binding - Generic type support for strongly-typed commands
  • Built-in Authentication - Support for role-based and claim-based authorization
  • Authorization Attributes - Use [Authorize], [AllowAnonymous], [ClaimRequirement]
  • Automatic JSON Serialization - Consistent handling with type information
  • Extensible - Create custom authentication handlers for specialized logic
  • FluentValidation Ready - Compatible with validation frameworks
  • Production-Ready - Battle-tested quality code

๐Ÿ“ฆ Installation

NuGet Package Manager

Install-Package CommandModelBinder

.NET CLI

dotnet add package CommandModelBinder

The package is available on NuGet.

โšก Quick Start

1. Define Your Command Interface

public interface IMyCommand { }

2. Create Commands

public class CreateUserCommand : IMyCommand
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

3. Register in Program.cs

using CommandModelBinder;

builder.Services.AddControllers(options =>
{
    options.ModelBinderProviders.Insert(0,
        new RequestCommandModelBinderProvider<IMyCommand>(
            new List<ICommandAuthentication> 
            { 
                new DefaultCommandAuthentication() 
            }));
});

4. Use in Your Controller

[ApiController]
[Route("api/users")]
public class UserController : ControllerBase
{
    [HttpPost("create")]
    public IActionResult Create([FromBody] IMyCommand command)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        if (command is CreateUserCommand createCmd)
        {
            // Process command
            return Ok($"User {createCmd.FirstName} created");
        }

        return BadRequest();
    }
}

๐Ÿ”’ Authentication Examples

Anonymous Access

[AllowAnonymous]
public class PublicSearchCommand : IMyCommand { }

Role-Based Authorization

[Authorize(Roles = "Administrator")]
public class AdminCommand : IMyCommand { }

Claim-Based Authorization

[ClaimRequirement("Department", "IT")]
public class ITCommand : IMyCommand { }

๐Ÿ—๏ธ Architecture

Core Components

Component Purpose
RequestCommandModelBinderProvider<T> Factory for creating model binders
RequestCommandModelBinder<T> Core binding and deserialization logic
ICommandAuthentication Extensible authentication interface
DefaultCommandAuthentication Standard authentication implementation
CommandSerializer Consistent JSON serialization
ClaimRequirementAttribute Claim-based authorization attribute

Request Flow

HTTP Request
    โ†“
JSON Deserialization
    โ†“
Type Validation
    โ†“
Authentication Check (Attributes)
    โ†“
ModelState Validation
    โ†“
Controller Action Parameter

๐Ÿ”ง Custom Authentication Handlers

Create specialized authentication logic:

public class CustomAuthHandler : ICommandAuthentication
{
    public bool Execute(ModelBindingContext bindingContext, object model)
    {
        // Your custom authentication logic
        if (/* your condition */)
            return true;

        bindingContext.ModelState.TryAddModelError("Unauthorized", "Custom error");
        return false;
    }
}

// Register it
var handlers = new List<ICommandAuthentication>
{
    new DefaultCommandAuthentication(),
    new CustomAuthHandler()
};

โœจ Key Features

1. Type Safety

Generic parameter T ensures only matching commands are bound:

public class RequestCommandModelBinder<IMyCommand> { }

2. Flexible Authentication

  • Role-based: [Authorize(Roles = "...")]
  • Claim-based: [ClaimRequirement("type", "value")]
  • Anonymous: [AllowAnonymous]
  • Custom: Implement ICommandAuthentication

3. Serialization

Automatic JSON serialization with:

  • Type name handling
  • CamelCase property names
  • Nested object support
  • Enum handling

4. Error Handling

Clear error messages in ModelState:

  • "no command." - Empty body
  • "not valid json." - Invalid JSON
  • "Cant parse to object." - Type mismatch
  • "User is not in role." - Authorization failure
  • "User does not have claim." - Claim mismatch

๐Ÿ“‹ Requirements

  • .NET Version: 9.0 or later
  • ASP.NET Core: 9.0 compatible
  • Dependencies:
    • Microsoft.AspNetCore.Authorization
    • Microsoft.AspNetCore.Mvc.Abstractions
    • Microsoft.AspNetCore.Mvc.Core
    • Newtonsoft.Json

๐Ÿงช Testing

The library includes comprehensive unit tests. Run tests with:

dotnet test

Example unit test:

[Test]
public async Task Bind_ValidCommand_ShouldSucceed()
{
    var command = new MyCommand();
    var json = command.SerializeCommand<IMyCommand>();
    var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
    
    var binder = new RequestCommandModelBinder<IMyCommand>(
        new[] { new DefaultCommandAuthentication() });
    var ctx = new DefaultModelBindingContext
    {
        ActionContext = new ActionContext 
        { 
            HttpContext = new DefaultHttpContext { Request = { Body = stream } } 
        },
        ModelState = new ModelStateDictionary()
    };

    await binder.BindModelAsync(ctx);

    Assert.That(ctx.ModelState.IsValid);
}

๐ŸŽฏ Use Cases

  • E-Commerce: Product catalog and order management
  • CRM Systems: Customer relationship management commands
  • Admin Panels: User management and configuration
  • API Gateways: Request routing and transformation
  • Microservices: Inter-service command dispatching
  • Real-time Applications: WebSocket command handling

๐Ÿš€ Best Practices

  1. Validate ModelState - Always check ModelState.IsValid before processing
  2. Default to Secure - Require authentication unless marked [AllowAnonymous]
  3. Use Claims over Roles - Claim-based authorization is more fine-grained
  4. Test All Paths - Test authenticated, unauthenticated, and wrong-role scenarios
  5. Document Requirements - Comment authorization requirements on commands
  6. Use DTOs - Map commands to domain models, don't use directly
  7. Handle Errors - Log authorization failures for security monitoring

๐Ÿ“ž Support

  • ๐Ÿ“– Documentation: See links above
  • ๐Ÿ› Issues: GitHub Issues
  • ๐Ÿ’ฌ Questions: Post on GitHub Discussions
  • ๐Ÿ”ง Contributing: See CONTRIBUTING.md

๐Ÿ“„ License

This project is licensed under the MIT License. See LICENSE file for details.


Made with โค๏ธ for ASP.NET Core developers

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.0.4 154 1/12/2026
0.0.3 261 2/26/2025
0.0.2 287 2/18/2025
0.0.1 168 2/18/2025