CommandModelBinder 0.0.4
dotnet add package CommandModelBinder --version 0.0.4
NuGet\Install-Package CommandModelBinder -Version 0.0.4
<PackageReference Include="CommandModelBinder" Version="0.0.4" />
<PackageVersion Include="CommandModelBinder" Version="0.0.4" />
<PackageReference Include="CommandModelBinder" />
paket add CommandModelBinder --version 0.0.4
#r "nuget: CommandModelBinder, 0.0.4"
#:package CommandModelBinder@0.0.4
#addin nuget:?package=CommandModelBinder&version=0.0.4
#tool nuget:?package=CommandModelBinder&version=0.0.4
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
- Validate ModelState - Always check
ModelState.IsValidbefore processing - Default to Secure - Require authentication unless marked
[AllowAnonymous] - Use Claims over Roles - Claim-based authorization is more fine-grained
- Test All Paths - Test authenticated, unauthenticated, and wrong-role scenarios
- Document Requirements - Comment authorization requirements on commands
- Use DTOs - Map commands to domain models, don't use directly
- 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.
๐ Links
- GitHub: https://github.com/a-t-k/CommandModelBinder
- NuGet: https://www.nuget.org/packages/CommandModelBinder/
- Issues: https://github.com/a-t-k/CommandModelBinder/issues
Made with โค๏ธ for ASP.NET Core developers
| Product | Versions 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. |
-
net10.0
- Microsoft.AspNetCore.Authorization (>= 9.0.2)
- Microsoft.AspNetCore.Mvc.Abstractions (>= 2.3.0)
- Microsoft.AspNetCore.Mvc.Core (>= 2.3.0)
- Newtonsoft.Json (>= 13.0.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.