Skip to main content

Routing - Mapping URLs to Code

Level: Beginner

ℹ️ Where This Fits

Routing connects URLs to code. Learn this before controllers, actions, model binding, and Web API endpoints.

ℹ️ What You'll Learn
  • Routing purpose: Match URL pattern + HTTP method to C# handler code
  • MapGet("/students", ...): Handle GET requests to /students (list all)
  • MapPost("/students", ...): Handle POST requests to /students (create new)
  • MapPut("/students/{id}", ...): Handle PUT requests to /students/101 (update one)
  • MapDelete("/students/{id}", ...): Handle DELETE requests to /students/101 (delete one)
  • Route parameters: {id} captures value from URL (GET /students/101 → id=101)
  • Route constraints: {id:int} only matches integer (/students/abc won't match)
  • Query string vs route: /students/101 is route (identifies resource), /students?class=10A is query (filter)
  • REST conventions: Use nouns (/students), not verbs (/getStudents). HTTP method implies action
  • School Management routes: GET /students, POST /students, GET /classes/:classId/students, POST /attendance, GET /reports/fees
  • Multiple parameters: Route can capture className and studentId from URL path segments
  • Optional parameters: Route parameters can be optional using route constraints for pagination
  • Debugging routing: Catch-all routes show unmatched URL patterns for troubleshooting

What is Routing?

Routing is how ASP.NET Core decides which C# code should run for a URL.

Example:

GET /students/101

Routing matches this to:

app.MapGet("/students/{id}", (int id) => ...);

Then ASP.NET Core passes:

id = 101

Basic Routes

💻 Try It — Console App
💡 Add these routes in Program.cs.⌥ GitHub
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "SchoolPortal Home");

app.MapGet("/students", () => "All students");

app.MapGet("/teachers", () => "All teachers");

app.Run();
URLHandler
/Home route
/studentsStudents route
/teachersTeachers route

Route Parameters

Route parameters capture values from the URL.

app.MapGet("/students/{id}", (int id) =>
{
return $"Student id is {id}";
});

Request:

/students/101

Result:

id = 101

Multiple Parameters

app.MapGet("/classes/{className}/students/{studentId}",
(string className, int studentId) =>
{
return $"Class: {className}, Student: {studentId}";
});

Request:

/classes/10A/students/101

Result:

className = 10A
studentId = 101

HTTP Methods and Routes

The same URL can behave differently based on HTTP method.

MethodRouteMeaning
GET/studentsRead students
POST/studentsCreate student
GET/students/101Read one student
PUT/students/101Update student
DELETE/students/101Delete student
app.MapGet("/students", () => "Get all students");

app.MapPost("/students", () => "Create student");

app.MapGet("/students/{id}", (int id) => $"Get student {id}");

app.MapPut("/students/{id}", (int id) => $"Update student {id}");

app.MapDelete("/students/{id}", (int id) => $"Delete student {id}");

Route Constraints

Constraints limit what values a route accepts.

app.MapGet("/students/{id:int}", (int id) =>
{
return $"Student {id}";
});

This matches:

/students/101

This does not match:

/students/abc

Common constraints:

ConstraintExampleMeaning
int{id:int}Must be integer
guid{id:guid}Must be GUID
min{id:min(1)}Minimum value
alpha{name:alpha}Letters only

Query String vs Route Parameter

Route parameter:

/students/101

Use when the value identifies a specific resource.

Query string:

/students?className=10A&status=active

Use for filters, sorting, searching, and paging.

Example:

app.MapGet("/students", (string? className, string? status) =>
{
return $"Class: {className}, Status: {status}";
});

School Management Route Examples

FeatureRoute
Get all studentsGET /students
Get one studentGET /students/{id}
Add studentPOST /students
Update studentPUT /students/{id}
Get class studentsGET /classes/{classId}/students
Mark attendancePOST /attendance
Get monthly reportGET /reports/monthly-fees?month=5&year=2026

Good Route Design

Prefer nouns:

/students
/teachers
/attendance
/reports

Avoid action-heavy names:

/getStudents
/createStudent
/deleteStudentById

HTTP method already tells the action.

Minimal API Routing vs Controller Routing

Minimal API:

app.MapGet("/students/{id}", (int id) => $"Student {id}");

Controller route:

[ApiController]
[Route("api/students")]
public class StudentsController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetStudent(int id)
{
return Ok($"Student {id}");
}
}

Both use routing. Controllers organize routes better in larger projects.

Common Beginner Mistakes

MistakeBetter Approach
/getStudent/101GET /students/101
/student/createPOST /students
Using route values for filtersUse query string for filters
No route constraintsUse {id:int} where needed
Very long route namesKeep routes readable and resource-based
Mixing singular/plural randomlyPrefer plural resources like /students

What to Remember

Routing = URL + HTTP method -> C# handler
Route parameter = value inside path
Query string = filters/search/paging
Constraint = rule for route value
🎯 Interview Favourite

Q: How does routing work in ASP.NET Core?

Good Answer: "Routing maps an incoming HTTP request to the correct endpoint or controller action. ASP.NET Core checks the HTTP method and URL path against route patterns like /students/{id}. Values in the URL can be captured as route parameters and passed to the handler. Routes can also use constraints such as {id:int}. In Web API design, routes usually represent resources, while HTTP methods represent actions."

Practice Before Next Article

Create routes for:

  1. Get all teachers.
  2. Get teacher by id.
  3. Get students in a class.
  4. Mark attendance.
  5. Get fee report by month and year using query string.
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on ASP.NET Core routing. Try these prompts:

  • "Create REST-style routes for a School Management System"
  • "Explain route parameters vs query strings"
  • "What are route constraints?"
  • "Review these routes and make them REST friendly"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

-> Dependency Injection (DI)

nexcoding.in