Routing in Web API
Learn how routing works in ASP.NET Core Web API and how to define clean, flexible, and meaningful API endpoints. Routing determines how HTTP requests are mapped to controller actions.
Part 1: What Is Routing?
Routing is the process of matching an incoming HTTP request URL to a specific controller action. It tells the application which code should handle the request.
In Web API, routing is essential because APIs rely entirely on URLs and HTTP methods.
Part 2: Attribute Routing
ASP.NET Core Web API uses attribute routing, where routes are defined using attributes directly on controllers and actions.
[Route("api/[controller]")]
public class StudentApiController : ControllerBase
This sets the base route to /api/studentapi.
Part 3: Defining Routes for Actions
Each action method can define its own route using HTTP method attributes.
public IEnumerable<string> GetAll()
{
return new string[] { "Alice", "Bob" };
}
[HttpGet("{id}")]
public string GetById(int id)
{
return "Student " + id;
}
These routes allow:
GET /api/studentapiGET /api/studentapi/1
Part 4: Route Parameters
Route parameters allow dynamic values to be passed through the URL.
The {id} placeholder is replaced with actual values in the request.
Part 5: Combining Routes and HTTP Methods
Web API routes are often combined with HTTP methods to define clear operations.
| HTTP Method | Route | Purpose |
|---|---|---|
| GET | /api/students | Retrieve all students |
| GET | /api/students/1 | Retrieve a specific student |
| POST | /api/students | Create a new student |
| PUT | /api/students/1 | Update a student |
| DELETE | /api/students/1 | Delete a student |
Part 6: Route Naming Best Practices
Good API design uses clear and consistent naming conventions.
- Use plural nouns (e.g.,
/students) - Keep routes simple and readable
- Avoid verbs in URLs
- Use HTTP methods to define actions
This makes your API easier to understand and maintain.
Part 7: Routing in the Student Project
In your Student CRUD API, routing allows you to expose data endpoints:
- Retrieve student lists
- Access individual student records
- Create and update records
- Delete records
Proper routing design makes your API professional and easy to use.
Part 8: Best Practices
- Use attribute routing consistently
- Keep routes simple and meaningful
- Use route parameters for dynamic data
- Follow RESTful conventions
- Test your routes thoroughly
Good routing design is the foundation of a well-structured API.
Summary
Routing is a core concept in ASP.NET Core Web API. It defines how requests are mapped to actions and ensures your API endpoints are clear and consistent. By mastering routing, you can build clean, scalable, and easy-to-use APIs.