ASP.NET Core Web API Interview Question #78

What are route constraints?

Routing, Versioning, OpenAPI/Swagger & API Documentation Mid-Level Intermediate

Quick Interview Answer

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

Detailed Explanation

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

Constraints are primarily for route disambiguation and matching. They should not replace normal input validation or business-rule validation.

Code Example

[HttpGet("{id:int}")]
public IActionResult GetById(int id) => Ok();

[HttpGet("{code:length(6)}")]
public IActionResult GetByCode(string code) => Ok();