MOTOSHARE ๐Ÿš—๐Ÿ๏ธ
Turning Idle Vehicles into Shared Rides & Earnings

From Idle to Income. From Parked to Purpose.
Earn by Sharing, Ride by Renting.
Where Owners Earn, Riders Move.
Owners Earn. Riders Move. Motoshare Connects.

With Motoshare, every parked vehicle finds a purpose. Owners earn. Renters ride.
๐Ÿš€ Everyone wins.

Start Your Journey with Motoshare

AspNetCore.Scalar Explained: Modern Input Validation and Binding for .NET Web Apps

๐Ÿ“Œ What is AspNetCore.Scalar?

AspNetCore.Scalar is a lightweight, extensible, and highly-focused library for ASP.NET Core applications that simplifies model binding, input validation, and data sanitization at the property level.

It introduces the concept of “Scalars”, which are strongly-typed wrappers around primitive data types like strings, integers, booleans, etc., adding value like automatic validation, normalization, and rich error handling โ€” all without cluttering your core domain models.

In simple terms:

AspNetCore.Scalar helps you validate and normalize user input early, safely, and elegantly in your ASP.NET Core Web APIs and MVC apps.

Instead of spreading validation logic across your controllers, services, or view models, Scalar centralizes and automates it, keeping your application clean, secure, and easy to maintain.


๐Ÿ“Œ Major Use Cases of AspNetCore.Scalar

You can use AspNetCore.Scalar in a wide range of modern ASP.NET Core application scenarios:

  • Web API Input Validation
    Validate user-provided API request fields (e.g., email addresses, usernames, phone numbers) early during model binding.
  • Sanitize User Input
    Normalize or clean up raw data inputs like trimming whitespaces, enforcing case rules (lowercase, uppercase), or formatting numbers before they hit your application logic.
  • Microservices Input Contracts
    Enforce strict input contracts between services by making sure incoming data follows expected formats and constraints.
  • Security Hardening
    Prevent injection attacks and other input-related vulnerabilities by validating and sanitizing at the first point of entry.
  • Domain-Driven Design (DDD)
    Encapsulate validation rules inside value objects without bloating the domain entities.
  • Developer Productivity
    Reduce repetitive validation code and avoid cluttering controllers and DTOs with manual if-else checks.
  • Error Reporting
    Provide clear and structured error messages on invalid user input automatically.

Overall, AspNetCore.Scalar is ideal for any project where input validation, data quality, and code maintainability are top priorities.


๐Ÿ“Œ How AspNetCore.Scalar Works (Architecture Overview)

AspNetCore.Scalar operates through a simple but powerful architectural flow:

๐Ÿ”น Core Components:

  • Scalar Types
    Custom classes that wrap a primitive type (like Email, PhoneNumber, Username).
  • Scalar Model Binders
    Intercept incoming HTTP request data during the ASP.NET Core model binding pipeline and instantiate scalar types automatically.
  • Scalar Validators
    Run predefined or custom validation rules (length checks, format validation, etc.) on the bound input data.
  • Scalar Normalizers
    Optionally sanitize/transform input (e.g., trimming spaces, converting to lowercase).
  • Integration with ModelState
    Scalar errors are pushed automatically into ModelState for seamless error reporting in APIs or MVC views.

๐Ÿ› ๏ธ Internal Workflow:

  1. Request data (query, body, route) arrives.
  2. Model binding detects scalar types.
  3. Scalars validate and normalize the data.
  4. If validation passes, the scalar is injected into the controller action.
  5. If validation fails, errors are added to ModelState, and appropriate HTTP 400 responses are generated.

This tight integration allows input processing before your application logic sees any data โ€” keeping your business layer pure and safe.


๐Ÿ“Œ Basic Workflow of AspNetCore.Scalar

Hereโ€™s how a typical AspNetCore.Scalar interaction looks like:

  1. Define a Scalar Class
    Create a strongly typed wrapper for a specific kind of input (like EmailAddress, Username).
  2. Configure Scalar Bindings
    Register scalar types into the ASP.NET Core dependency injection system.
  3. Bind Scalars in Controllers
    Use scalar types as parameters in API or MVC controller actions.
  4. Validation and Normalization Happen Automatically
    Scalars validate incoming user input at the model-binding stage.
  5. Handle Errors
    If input fails validation, ASP.NET Core automatically returns an error response, or you can customize the response.
  6. Use Validated Data
    Valid scalar values are available in controller methods for further business processing.

๐Ÿ“Œ Step-by-Step Getting Started Guide for AspNetCore.Scalar

Hereโ€™s how you can easily get started:


1๏ธโƒฃ Install AspNetCore.Scalar

You can install via NuGet:

dotnet add package AspNetCore.Scalar

Or in Visual Studio, search for AspNetCore.Scalar in the NuGet package manager.


2๏ธโƒฃ Create Your First Scalar

using Scalar;

public class Email : ScalarOf<string>
{
    public Email(string value) : base(value) {}

    protected override void Validate()
    {
        if (string.IsNullOrWhiteSpace(Value))
            throw new ScalarValidationException("Email is required.");

        if (!Value.Contains("@"))
            throw new ScalarValidationException("Email must contain @ symbol.");
    }

    protected override string Normalize(string value)
    {
        return value.Trim().ToLower();
    }
}


3๏ธโƒฃ Register Scalars in Startup

In your Program.cs or Startup.cs, register scalar model binding:

builder.Services.AddScalarModelBinder();


4๏ธโƒฃ Use Scalars in Controller Actions

[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
    [HttpPost]
    public IActionResult Register([FromBody] Email email)
    {
        // If this point is reached, email is already validated
        return Ok($"Registered user with email: {email.Value}");
    }
}


5๏ธโƒฃ Customize Error Responses (Optional)

Customize model state error behavior:

builder.Services.Configure<ApiBehaviorOptions>(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        var errors = context.ModelState.Values
                       .SelectMany(x => x.Errors)
                       .Select(x => x.ErrorMessage);
        return new BadRequestObjectResult(new { Errors = errors });
    };
});

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x