Web Api Routing

In this article, we are learning to map action for incoming Http URLs via defined routes.

How Routing Work?

  • When web API receives an HTTP Request by the controller, it goes to the routing table to find the matching route.
  • Once route matches as per HTTP request, then this route is mapped to a specific action in a controller,
  • Which is responsible execute to creating a response to the client for the requested resource URL

The routing table is a collection of routes defined in the WebApiConfig.cs file and placed in the App_Start directory in the project. There you can also  find one default route, which is created by default while creating a project.

  • Types of Web API Routing :
    1. Convention-based Routing
    2. Attribute Routing

Convention-based Routing

  • The convention-based routing in Web API uses the routing to the route which controller and action method to execute.
  • At least one route was added to the routing table to handle various HTTP requests.
  •  App_Start folder with default route as shown below.
 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 }
            );
}
  • The MapHttpRoute() extension method creates a IHttpRoute and HttpRouteCollection.
  • Create a new route as shown below.
    public static void Register(HttpConfiguration config)
          {
              // Enable attribute routing
              config.MapHttpAttributeRoutes();
    
              // define route
              IHttpRoute defaultRoute = config.Routes.CreateRoute
                                        ( 
                                          "api/{controller}/{id}",
                                           new{id = RouteParameter.Optional},
                                            null);
    
             // Add route
             config.Routes.Add("DefaultApi", defaultRoute);
                                         }
           }
  • The following table lists parameters of MapHttpRoute() method.
Verb Usage Example Url
GET Used for getting data in a read only context. localhost/users OR localhost/users/<user_name> for a specific resource (think get by id).
POST Used to create a new resource. localhost/users/<user_name> with parameters of POST body containing parameters.
PUT Used to update an existing resource. localhost/users/<user_name> with parameters of PUT body containing parameters.
DELETE Used to delete a resource. localhost/users/<user_name>

Configure Multiple Routes

  • Configure multiple route in the web API using HttpConfiguration object.
  • The following example of multiple routes.
public static void Register(HttpConfiguration config)
       {
               config.MapHttpAttributeRoutes();

               // product route
               config.Routes.MapHttpRoute(
                   name: "Product",
                   routeTemplate: "api/getproduct/{id}",
                   defaults: new { controller = "product", id = RouteParameter.Optional },
                   constraints: new { id = "/d+" }
               );

               // default route
               config.Routes.MapHttpRoute(
                   name: "DefaultApi",
                   routeTemplate: "api/{controller}/{id}",
                   defaults: new { id = RouteParameter.Optional }
               );
       }
  • In the this example, Product route is configured before DefaultApi route.
  • So any incoming request will be matched with the Product route first and if incoming request URL does not match with it then only it will be matched with DefaultApi route.

Attribute Routing

  • Attribute routing uses [Route()] attribute to define routes.
  • The Route attribute can be applied on any controller or action method.
  • The following example of attribute routing.
public class ProductController : ApiController
{
    [Route("api/student/names")]
                public IEnumerable<string> Get()
    {
                return new string[] { "Laptop", "PC" };
    }
}

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories