In enterprise ASP.NET Core MVC applications, two recurring cross-cutting problems tend to leak into every controller action when handled ad hoc:

  1. Repetitive & Ambiguous Input Parsing: Parsing composite tokens, normalized identifiers, or structured query/header values into strongly typed domain value objects (such as a DateRangeFilter or TenantScopedCode) inside individual controller actions leads to inconsistent parsing, missing validation errors, and duplicated logic.

  2. Ad-Hoc Authorization & Scope Checks: Checking whether a caller is authenticated, holds a required scope/role, or is permitted to operate on a requested tenant/organization inside each action method risks accidental omission on a newly added endpoint.

Pairing a custom IModelBinder + IModelBinderProvider with an IAsyncAuthorizationFilter (or attribute-driven IAsyncAuthorizationFilter via IFilterFactory) solves both cleanly. Authorization filters run first in the MVC filter pipeline—short-circuiting unauthorized or out-of-scope requests before model binding and action execution—while a custom model binder transforms bound request values into strongly typed, validated parameters that MVC's ModelState pipeline understands natively.

1. Architectural Blueprint & Pipeline Execution Order

Plaintext

C#
Incoming HTTP Request (with X-Scope-Role / X-Allowed-Tenants & query/route params)
   │
   ▼
[Routing] ──> [Endpoint Selected]
                     │
                     ▼
   ┌──────────────────────────────────────────────────────────┐
   │ 1. IAsyncAuthorizationFilter.OnAuthorizationAsync()      │
   │    • Runs FIRST in the MVC filter pipeline               │
   │    • Verifies required scope & tenant access             │
   │    • Unauthorized/Forbidden? Sets context.Result =       │
   │      401 / 403 ProblemDetails & short-circuits early     │
   └─────────────────────────┬────────────────────────────────┘
                             │ (Authorized)
                             ▼
   ┌──────────────────────────────────────────────────────────┐
   │ 2. Custom IModelBinder (via IModelBinderProvider)        │
   │    • Parses & normalizes raw input (e.g., DateRangeFilter) │
   │    • Records ModelState errors on invalid format/range   │
   │    • Populates strongly typed action parameter           │
   └─────────────────────────┬────────────────────────────────┘
                             │
                             ▼
   ┌──────────────────────────────────────────────────────────┐
   │ 3. MVC Controller Action                                 │
   │    • Receives pre-validated strongly typed parameters    │
   │    • Focuses purely on domain/query orchestration        │
   └──────────────────────────────────────────────────────────┘

Concern

MVC Pipeline Stage

Key Design Rule

Scope & Tenant Authorization

IAsyncAuthorizationFilter (runs before model binding and action filters)

Short-circuit unauthorized or out-of-scope requests immediately with 401 or 403 ProblemDetails.

Custom Value Binding

IModelBinder + IModelBinderProvider (inserted early in MvcOptions.ModelBinderProviders)

Populate bindingContext.ModelState.TryAddModelError(...) on invalid input rather than throwing raw exceptions or returning HTTP results directly inside the binder.

Action Execution

Controller action method

Assume caller scope/tenant is verified and strongly typed inputs are bound; check ModelState.IsValid cleanly.

2. Custom IModelBinder and IModelBinderProvider for DateRangeFilter

Let's build a DateRangeFilter value object that binds from query parameters (from and to in YYYY-MM-DD format), normalizes UTC day boundaries, rejects inverted ranges (from > to) or ranges exceeding a maximum window (maxDays), and records clean ModelState validation errors when parsing fails.

C#

C#
using System.Globalization;
using Microsoft.AspNetCore.Mvc.ModelBinding;

public sealed record DateRangeFilter(
    DateOnly FromDate,
    DateOnly ToDate
)
{
    public DateTimeOffset StartUtc =>
        new(FromDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);

    public DateTimeOffset EndExclusiveUtc =>
        new(ToDate.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);

    public int InclusiveDays =>
        (ToDate.DayNumber - FromDate.DayNumber) + 1;
}

public sealed class DateRangeFilterModelBinder : IModelBinder
{
    private const int MaxRangeDays = 366;

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        ArgumentNullException.ThrowIfNull(bindingContext);

        ValueProviderResult fromResult = bindingContext.ValueProvider.GetValue("from");
        ValueProviderResult toResult = bindingContext.ValueProvider.GetValue("to");

        // If neither parameter is supplied, default to the last 30 UTC days
        if (fromResult == ValueProviderResult.None && toResult == ValueProviderResult.None)
        {
            DateOnly todayUtc = DateOnly.FromDateTime(DateTime.UtcNow);
            bindingContext.Result = ModelBindingResult.Success(
                new DateRangeFilter(todayUtc.AddDays(-29), todayUtc));
            return Task.CompletedTask;
        }

        if (fromResult == ValueProviderResult.None || string.IsNullOrWhiteSpace(fromResult.FirstValue))
        {
            bindingContext.ModelState.TryAddModelError(
                bindingContext.ModelName,
                "The 'from' query parameter (YYYY-MM-DD) is required when specifying a date range.");
            return Task.CompletedTask;
        }

        if (toResult == ValueProviderResult.None || string.IsNullOrWhiteSpace(toResult.FirstValue))
        {
            bindingContext.ModelState.TryAddModelError(
                bindingContext.ModelName,
                "The 'to' query parameter (YYYY-MM-DD) is required when specifying a date range.");
            return Task.CompletedTask;
        }

        if (!DateOnly.TryParseExact(
                fromResult.FirstValue.Trim(),
                "yyyy-MM-dd",
                CultureInfo.InvariantCulture,
                DateTimeStyles.None,
                out DateOnly fromDate))
        {
            bindingContext.ModelState.TryAddModelError(
                bindingContext.ModelName,
                $"Invalid 'from' date '{fromResult.FirstValue}'. Expected format YYYY-MM-DD.");
            return Task.CompletedTask;
        }

        if (!DateOnly.TryParseExact(
                toResult.FirstValue.Trim(),
                "yyyy-MM-dd",
                CultureInfo.InvariantCulture,
                DateTimeStyles.None,
                out DateOnly toDate))
        {
            bindingContext.ModelState.TryAddModelError(
                bindingContext.ModelName,
                $"Invalid 'to' date '{toResult.FirstValue}'. Expected format YYYY-MM-DD.");
            return Task.CompletedTask;
        }

        if (fromDate > toDate)
        {
            bindingContext.ModelState.TryAddModelError(
                bindingContext.ModelName,
                "The 'from' date must not be later than the 'to' date.");
            return Task.CompletedTask;
        }

        int spanDays = (toDate.DayNumber - fromDate.DayNumber) + 1;
        if (spanDays > MaxRangeDays)
        {
            bindingContext.ModelState.TryAddModelError(
                bindingContext.ModelName,
                $"Date range cannot exceed {MaxRangeDays} days (requested {spanDays} days).");
            return Task.CompletedTask;
        }

        bindingContext.Result = ModelBindingResult.Success(new DateRangeFilter(fromDate, toDate));
        return Task.CompletedTask;
    }
}

public sealed class DateRangeFilterModelBinderProvider : IModelBinderProvider
{
    public IModelBinder? GetBinder(ModelBinderProviderContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        return context.Metadata.ModelType == typeof(DateRangeFilter)
            ? new DateRangeFilterModelBinder()
            : null;
    }
}

3. IAsyncAuthorizationFilter for Scope and Tenant Access Enforcement

Let's implement a [RequireTenantScope("reports.read")] attribute (IFilterFactory) and TenantScopeAuthorizationFilter (IAsyncAuthorizationFilter). It verifies that the caller presents a valid scope and is authorized for the requested tenant (from X-Tenant-Id header or route value), returning RFC 9457 401 Unauthorized or 403 Forbidden ProblemDetails immediately on failure.

C#

C#
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class RequireTenantScopeAttribute : Attribute, IFilterFactory
{
    public string RequiredScope { get; }

    public RequireTenantScopeAttribute(string requiredScope)
    {
        if (string.IsNullOrWhiteSpace(requiredScope))
        {
            throw new ArgumentException("Required scope cannot be empty.", nameof(requiredScope));
        }

        RequiredScope = requiredScope.Trim();
    }

    public bool IsReusable => true;

    public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
    {
        var logger = serviceProvider.GetRequiredService<ILogger<TenantScopeAuthorizationFilter>>();
        return new TenantScopeAuthorizationFilter(RequiredScope, logger);
    }
}

public sealed class TenantScopeAuthorizationFilter : IAsyncAuthorizationFilter
{
    private readonly string _requiredScope;
    private readonly ILogger<TenantScopeAuthorizationFilter> _logger;

    public TenantScopeAuthorizationFilter(
        string requiredScope,
        ILogger<TenantScopeAuthorizationFilter> logger)
    {
        _requiredScope = requiredScope;
        _logger = logger;
    }

    public Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        ArgumentNullException.ThrowIfNull(context);

        HttpContext httpContext = context.HttpContext;

        // Read caller scope & allowed tenant list from headers (or claims in production auth)
        string grantedScopesHeader = httpContext.Request.Headers["X-Granted-Scopes"].ToString();
        string allowedTenantsHeader = httpContext.Request.Headers["X-Allowed-Tenants"].ToString();
        string requestedTenant = httpContext.Request.Headers["X-Tenant-Id"].ToString().Trim();

        if (string.IsNullOrWhiteSpace(grantedScopesHeader))
        {
            context.Result = CreateProblemResult(
                httpContext,
                StatusCodes.Status401Unauthorized,
                "https://problems.example.local/errors/missing-scope",
                "Unauthorized",
                "Missing caller scope credentials.");
            return Task.CompletedTask;
        }

        var grantedScopes = grantedScopesHeader
            .Split([',', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
            .ToHashSet(StringComparer.OrdinalIgnoreCase);

        if (!grantedScopes.Contains(_requiredScope))
        {
            _logger.LogWarning(
                "Authorization denied on {Path}: missing required scope '{RequiredScope}'.",
                httpContext.Request.Path,
                _requiredScope);

            context.Result = CreateProblemResult(
                httpContext,
                StatusCodes.Status403Forbidden,
                "https://problems.example.local/errors/insufficient-scope",
                "Forbidden",
                $"Caller lacks the required '{_requiredScope}' scope.");
            return Task.CompletedTask;
        }

        if (!string.IsNullOrWhiteSpace(requestedTenant))
        {
            var allowedTenants = allowedTenantsHeader
                .Split([',', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
                .ToHashSet(StringComparer.OrdinalIgnoreCase);

            if (!allowedTenants.Contains(requestedTenant))
            {
                _logger.LogWarning(
                    "Tenant access denied on {Path}: tenant '{RequestedTenant}' not permitted.",
                    httpContext.Request.Path,
                    requestedTenant);

                context.Result = CreateProblemResult(
                    httpContext,
                    StatusCodes.Status403Forbidden,
                    "https://problems.example.local/errors/tenant-forbidden",
                    "Tenant Access Denied",
                    $"Access to tenant '{requestedTenant}' is not permitted.");
                return Task.CompletedTask;
            }
        }

        return Task.CompletedTask;
    }

    private static ObjectResult CreateProblemResult(
        HttpContext httpContext,
        int statusCode,
        string typeUri,
        string title,
        string detail)
    {
        string traceId = Activity.Current?.TraceId.ToString() ?? httpContext.TraceIdentifier;

        var problem = new ProblemDetails
        {
            Status = statusCode,
            Type = typeUri,
            Title = title,
            Detail = detail,
            Instance = httpContext.Request.Path.Value
        };
        problem.Extensions["traceId"] = traceId;

        return new ObjectResult(problem)
        {
            StatusCode = statusCode,
            ContentTypes = { "application/problem+json" }
        };
    }
}

4. MVC Controller and Program.cs Registration

Let's wire DateRangeFilterModelBinderProvider at index 0 of MvcOptions.ModelBinderProviders (so it always takes precedence for DateRangeFilter), and protect TenantUsageController with [RequireTenantScope("usage.read")].

Controller (TenantUsageController.cs)

C#

C#
using Microsoft.AspNetCore.Mvc;

public sealed record UsageSummaryResponse(
    string TenantId,
    DateOnly FromDate,
    DateOnly ToDate,
    int TotalDays,
    long EstimatedEvents
);

[ApiController]
[Route("api/tenants/usage")]
[RequireTenantScope("usage.read")]
public sealed class TenantUsageController : ControllerBase
{
    [HttpGet("summary")]
    public IActionResult GetSummary([FromQuery] DateRangeFilter range)
    {
        if (!ModelState.IsValid)
        {
            return ValidationProblem(ModelState);
        }

        string tenantId = HttpContext.Request.Headers["X-Tenant-Id"].ToString().Trim();
        if (string.IsNullOrWhiteSpace(tenantId))
        {
            tenantId = "default-tenant";
        }

        var response = new UsageSummaryResponse(
            TenantId: tenantId,
            FromDate: range.FromDate,
            ToDate: range.ToDate,
            TotalDays: range.InclusiveDays,
            EstimatedEvents: range.InclusiveDays * 420L);

        return Ok(response);
    }
}

Application Setup (Program.cs)

C#

C#
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews(options =>
{
    // Insert custom binder provider at the front so DateRangeFilter always binds via our binder
    options.ModelBinderProviders.Insert(0, new DateRangeFilterModelBinderProvider());
});

var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllers();

app.Run();

public partial class Program { }

5. End-to-End Integration Testing with WebApplicationFactory<Program>

Testing against WebApplicationFactory<Program> verifies authorization enforcement (401 / 403 ProblemDetails), custom model binding validation errors (400 validation problem when from > to), and successful strongly typed binding when valid scope, tenant, and dates are supplied.

C#

C#
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public sealed class CustomBinderAndAuthFilterTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly WebApplicationFactory<Program> _factory;

    public CustomBinderAndAuthFilterTests(WebApplicationFactory<Program> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task GetSummary_WithoutScope_Returns401ProblemDetails()
    {
        using HttpClient client = _factory.CreateClient();

        HttpResponseMessage response = await client.GetAsync("/api/tenants/usage/summary?from=2026-11-01&to=2026-11-10");

        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
        Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
    }

    [Fact]
    public async Task GetSummary_ForDisallowedTenant_Returns403ProblemDetails()
    {
        using HttpClient client = _factory.CreateClient();
        using var request = new HttpRequestMessage(
            HttpMethod.Get,
            "/api/tenants/usage/summary?from=2026-11-01&to=2026-11-10");

        request.Headers.Add("X-Granted-Scopes", "usage.read");
        request.Headers.Add("X-Allowed-Tenants", "tenant-alpha,tenant-beta");
        request.Headers.Add("X-Tenant-Id", "tenant-gamma");

        HttpResponseMessage response = await client.SendAsync(request);

        Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
        Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
    }

    [Fact]
    public async Task GetSummary_WithInvertedDateRange_FailsCustomModelBindingWith400()
    {
        using HttpClient client = _factory.CreateClient();
        using var request = new HttpRequestMessage(
            HttpMethod.Get,
            "/api/tenants/usage/summary?from=2026-11-20&to=2026-11-10");

        request.Headers.Add("X-Granted-Scopes", "usage.read");
        request.Headers.Add("X-Allowed-Tenants", "tenant-alpha");
        request.Headers.Add("X-Tenant-Id", "tenant-alpha");

        HttpResponseMessage response = await client.SendAsync(request);

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        string body = await response.Content.ReadAsStringAsync();
        Assert.Contains("must not be later than", body, StringComparison.OrdinalIgnoreCase);
    }

    [Fact]
    public async Task GetSummary_WithValidScopeTenantAndDates_BindsDateRangeFilterAndReturnsSummary()
    {
        using HttpClient client = _factory.CreateClient();
        using var request = new HttpRequestMessage(
            HttpMethod.Get,
            "/api/tenants/usage/summary?from=2026-11-01&to=2026-11-05");

        request.Headers.Add("X-Granted-Scopes", "usage.read");
        request.Headers.Add("X-Allowed-Tenants", "tenant-alpha");
        request.Headers.Add("X-Tenant-Id", "tenant-alpha");

        HttpResponseMessage response = await client.SendAsync(request);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        UsageSummaryResponse? payload = await response.Content.ReadFromJsonAsync<UsageSummaryResponse>();
        Assert.NotNull(payload);
        Assert.Equal("tenant-alpha", payload.TenantId);
        Assert.Equal(5, payload.TotalDays);
        Assert.Equal(2100L, payload.EstimatedEvents);
    }
}

6. Conclusion

Combining a custom IModelBinder + IModelBinderProvider with an IAsyncAuthorizationFilter gives ASP.NET Core MVC controllers clean, declarative boundaries for both security and input normalization. Unauthorized or out-of-scope requests are stopped before model binding even runs, malformed or out-of-range inputs surface cleanly through ModelState validation, and controller actions stay focused on business logic rather than repetitive parsing or guard boilerplate.