ASP.NET Core Routing and Model Binding
On this page
Learning Objective
Use route templates and constraints, identify where each handler parameter comes from, bind request data to purpose-built types, and explain how mass assignment, also called overposting, happens and how to prevent it.
Concept Explanation
Routing maps a method and URL to a handler. A template like /api/notes/{id:int} captures a segment named id and constrains it to an integer, so a request for /api/notes/abc never reaches the handler and gets a 404. Constraints exist for guid, bool, datetime, min, max, and regex, and they are a first, cheap line of validation. Route templates are matched case-insensitively, and more specific templates win over general ones, so /api/notes/latest can coexist with /api/notes/{id}. The important habit is to keep URLs shaped around resources and use plural nouns, which Phase 3 covers in detail.
Model binding is the process of turning request data into method parameters. In minimal APIs the framework infers the source by type and position. Simple types that appear in the route template come from the route, other simple types come from the query string, complex types come from the JSON body, and registered services come from dependency injection. You can be explicit with FromRoute, FromQuery, FromHeader, FromBody, and FromServices attributes, and the AsParameters attribute lets you gather many parameters into a single record. For a JavaScript developer it is helpful to think of it as automatic destructuring of the request object into typed arguments.
Serialization defaults matter to the contract with your React client. ASP.NET Core uses System.Text.Json with web defaults: property names are camelCase on the wire, matching what TypeScript code expects, and matching is case-insensitive on input. Unknown properties in incoming JSON are ignored by default. That default is convenient, but it is also the root of the mass assignment problem when you bind requests straight to database entities. If your User entity has an IsAdmin property and your update endpoint binds the request body to User, a caller can simply include isAdmin true in the JSON and the framework will faithfully set it.
The defense is structural and simple: never bind requests to entities. Define a dedicated request type containing only the fields a caller is allowed to set, and copy those fields explicitly. That request type is the allowlist. As a second layer you can configure the serializer to reject unknown members using JsonUnmappedMemberHandling.Disallow, so a payload containing surprise fields fails with a 400 instead of being silently dropped. Route parameters are also user input: a numeric id in the URL is only an identifier, not proof that the caller may see that record, a point Phase 5 returns to under object-level authorization.
| Source | Attribute | Inferred when |
|---|---|---|
| Route | FromRoute | Parameter name matches a route template segment |
| Query string | FromQuery | Simple type not in the route template |
| Header | FromHeader | Never inferred, always explicit |
| Body | FromBody | A single complex type on POST, PUT, or PATCH |
| Service | FromServices | Type registered in the DI container |
| Bundle of parameters | AsParameters | Record grouping route, query and services |
Worked Example: Binding Sources and Closing an Overposting Hole
The first block shows a vulnerable update endpoint that binds directly to an entity. The second block fixes it with a request type and enables strict deserialization. A final snippet shows AsParameters for a search endpoint.
// Entity: has a privileged field that callers must never control.
public class UserAccount
{
public int Id { get; set; }
public string DisplayName { get; set; } = "";
public bool IsAdmin { get; set; }
}
// VULNERABLE: the body is deserialized straight onto the entity.
app.MapPut("/api/users/{id:int}", async (int id, UserAccount input, AppDb db) =>
{
var user = await db.Users.FindAsync(id);
if (user is null) return Results.NotFound();
user.DisplayName = input.DisplayName;
user.IsAdmin = input.IsAdmin; // attacker sends {"isAdmin": true}
await db.SaveChangesAsync();
return Results.NoContent();
});// SAFE: a dedicated request type is the allowlist of writable fields.
public record UpdateProfileRequest(string DisplayName);
app.MapPut("/api/users/{id:int}", async (int id, UpdateProfileRequest input, AppDb db, ClaimsPrincipal caller) =>
{
// The id in the URL is not proof of entitlement; check it against the caller (Phase 5).
var user = await db.Users.FindAsync(id);
if (user is null) return Results.NotFound();
user.DisplayName = input.DisplayName.Trim();
await db.SaveChangesAsync();
return Results.NoContent();
});
// Reject payloads that contain fields we do not define.
builder.Services.ConfigureHttpJsonOptions(o =>
o.SerializerOptions.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow);
// Gathering query and service parameters with AsParameters.
public record SearchQuery(string? Term, int Page = 1, int PageSize = 20);
app.MapGet("/api/notes", async ([AsParameters] SearchQuery q, NotesDb db) => { /* ... */ });With the safe version, a request body of displayName plus isAdmin true is rejected, and even if unknown-member handling were left at its default, the extra field would be ignored rather than assigned, because no code ever copies it.
Real-World Examples
- In March 2012, developer Egor Homakov used a mass assignment flaw in GitHub's Rails code to add his own SSH public key to the Rails organization's account and push a commit to the Rails repository, deliberately to demonstrate the problem after his warnings were dismissed. GitHub fixed it and the episode led Rails to change its defaults toward requiring an explicit allowlist of assignable attributes.
- The OWASP API Security Top 10 lists Broken Object Property Level Authorization, which includes mass assignment and excessive data exposure, as a top risk. Frameworks that bind requests directly onto persistence models make it easy to introduce, which is why using dedicated input and output types is the standard recommendation.
Review Questions & Answers
Mass assignment is when a client sets fields it was never meant to control by including them in the request. If the endpoint deserializes the body directly onto an entity, every public property of that entity, including flags like IsAdmin or Price, becomes settable by the caller. A dedicated request type contains only permitted fields, so the extra properties have nowhere to land.
The route constraint fails to match, so the request does not reach the handler and the framework returns 404. Constraints therefore give a free first filter for malformed identifiers before any code runs. They do not replace validation of ranges or business rules, but they keep obviously invalid input out.
For a minimal API endpoint, simple types that are not part of the route template are bound from the query string, so a request to /api/notes?page=2 supplies the value. If it is absent, the parameter takes its default if one exists, or the request fails with a 400 for a required parameter. You can make the source explicit with an attribute.
The identifier only says which record the caller is asking for, not whether they are permitted to see it. Anyone can change a number in a URL, so an endpoint that fetches by id without checking ownership or role exposes every record to any authenticated caller. Access checks must compare the record to the caller's identity and permissions on every request.