Routing is how Web API matches a URI to an action.
It routes an incoming HTTP request to a particular action method on a Web API controller.
It routes an incoming HTTP request to a particular action method on a Web API controller.
Web API supports two types of routing:
- Convention-based Routing
- Attribute Routing
Convention-based Routing
In the convention-based routing, Web API uses route templates to determine which controller and action method to execute. At least one route template must be added into route table in order to handle various HTTP requests.
Example:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Enable attribute routing
config.MapHttpAttributeRoutes();
// Add default route using convention-based routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Configure Multiple Routes
However, you can configure multiple routes in the Web API using HttpConfiguration object.
Attribute Routing
Attribute routing is supported in Web API 2. As the name implies, attribute routing uses [Route()] attribute to define routes. The
Route
attribute can be applied on any controller or action method.
In order to use attribute routing with Web API, it must be enabled in WebApiConfig by calling
config.MapHttpAttributeRoutes()
method.
Example:
public class StudentController : ApiController
{
[Route("api/student/names")]
public IEnumerable<string> Get()
{
return new string[] { "student1", "student2" };
}
}