ASP.NET Core Interview Question #106

What are route constraints?

Routing, Controllers & Model Binding Mid-Level Intermediate

Quick Interview Answer

Route constraints restrict which URL values can match a route parameter. Built-in constraints include int, guid, bool, datetime, length, min, max, and others.

Detailed Explanation

Route constraints restrict which URL values can match a route parameter. Built-in constraints include int, guid, bool, datetime, length, min, max, and others.

Constraints help routing distinguish between otherwise similar route patterns and reject values that do not fit the expected route shape.

They should primarily be used for route matching, not as a replacement for full business validation.

Code Example

[HttpGet("orders/{id:guid}")]
public IActionResult GetOrder(Guid id)
{
    return Ok(id);
}

[HttpGet("products/{id:int:min(1)}")]
public IActionResult GetProduct(int id)
{
    return Ok(id);
}