Routing in ASP.NET Web API is the process of mapping incoming HTTP requests to the appropriate controller actions. It determines how the application responds to a client request based on the URL and HTTP method used. Routing is a fundamental aspect of building RESTful services, as it allows you to define clean and meaningful URLs for your API endpoints.

How Routing Works

When a request is made to an ASP.NET Web API application, the routing engine examines the URL and HTTP method to determine which controller and action method should handle the request. The routing process involves the following steps:

  1. The incoming request is received by the ASP.NET runtime.
  2. The routing engine checks the defined routes in the application to find a match for the incoming URL.
  3. If a match is found, the routing engine invokes the corresponding controller action method.
  4. The action method processes the request and returns an appropriate response.

Default Routing Configuration

By default, ASP.NET Web API uses a convention-based routing system. The default route template is defined in the WebApiConfig.cs file, typically located in the App_Start folder. The default route template is as follows:

        
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

In this template:

  • api: This is a prefix that indicates the request is for the API.
  • {controller}: This placeholder is replaced with the name of the controller (without the "Controller" suffix).
  • {id}: This optional placeholder represents the ID of the resource being accessed.

Example of Routing in Action

Consider the following example of a ProductsController that handles requests related to products:

        
public class ProductsController : ApiController
{
// GET api/products
public IEnumerable<Product> Get()
{
return GetAllProducts(); // Fetch all products
}

// GET api/products/1
public IHttpActionResult Get(int id)
{
var product = GetProductById(id); // Fetch product by ID
if (product == null)
{
return NotFound(); // Return 404 if not found
}
return Ok(product); // Return the product
}
}

In this example:

  • A GET request to http://localhost:port/api/products will invoke the Get() method, returning a list of all products.
  • A GET request to http://localhost:port/api/products/1 will invoke the Get(int id) method, returning the product with ID 1.

Attribute Routing

In addition to convention-based routing, ASP.NET Web API also supports attribute routing, which allows you to define routes directly on the controller actions using attributes. This provides more control over the routing configuration.

        
public class ProductsController : ApiController
{
[HttpGet]
[Route("api/products")]
public IEnumerable<Product> GetAllProducts()
{
return GetAllProducts(); // Fetch all products
}

[HttpGet]
[Route("api/products/{id}")]
public IHttpActionResult GetProduct(int id)
{
var product = GetProductById(id); // Fetch product by ID
if (product == null)
{
return NotFound(); // Return 404 if not found
}
return Ok(product); // Return the product
}
}

In this example, the routes are defined using the [Route] attribute, allowing for more explicit control over the routing behavior. The routes are now directly associated with the action methods, making it easier to understand and manage the API endpoints.

Conclusion

Routing is a critical component of ASP.NET Web API that enables the mapping of HTTP requests to the appropriate controller actions. By utilizing both convention-based and attribute routing, developers can create clean, meaningful, and maintainable API endpoints that enhance the overall usability of the web services.