Web API Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

Routing Handled in ASP.NET MVC 5 Web API

Back to: Web API Tutorial

In ASP.NET MVC 5 Web API, routing is handled through a routing table that defines how incoming HTTP requests are mapped to controller actions. Routing enables developers to define URL patterns and associate them with specific actions.

Key Concepts in ASP.NET MVC 5 Web API Routing

  1. Route Table
    The route table is a collection of routes defined in the application. In Web API, routes are typically configured in the WebApiConfig class.

  2. Routing Mechanisms
    ASP.NET Web API supports two types of routing:

    • Convention-based Routing: Defined centrally in the WebApiConfig file.
    • Attribute Routing: Routes are defined using attributes directly on controller methods or controllers.

Convention-Based Routing

In the App_Start/WebApiConfig.cs file, you define routes in the Register method:

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 } );
}
}

Key Components:

  • routeTemplate: Specifies the URL pattern (api/{controller}/{id}).
  • defaults: Specifies default values for route parameters.
  • id: Optional parameter in the URL (e.g., api/products/5).

Attribute Routing

Attribute routing allows defining routes directly on the controller or its actions using [Route] or [Http...] attributes. This provides more control over the routes.

Enabling Attribute Routing:

To use attribute routing, add the following line in the WebApiConfig file:

config.MapHttpAttributeRoutes();

Example:

[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
// GET api/products [HttpGet, Route("")]
public IEnumerable GetAllProducts()
{
// Implementation
}
// GET api/products/{id}
[HttpGet, Route("{id:int}")]
public IHttpActionResult GetProductById(int id)
{
 // Implementation
}
// POST api/products [HttpPost, Route("")]
public IHttpActionResult CreateProduct(Product product)
{
// Implementation
}
}

Benefits:

  • Enables the definition of complex routes.
  • Routes can be easily customized for each action.
  • More readable and maintainable.

Route Constraints

Route constraints are used to restrict the format of route parameters. For example:

[Route("api/products/{id:int}")]
  • id:int: Ensures id is an integer.
  • Other constraints include string, guid, datetime, etc.

Routing in Action

When a request comes in, the routing engine:

  1. Matches the URL to the configured routes.
  2. Extracts the route parameters and maps them to controller action parameters.
  3. Calls the matching action method in the controller.

Example Workflow

  1. URL: http://example.com/api/products/5
  2. Route: api/{controller}/{id}
    • controller: ProductsController
    • id: 5
  3. Action Invoked: GetProductById(5)

Debugging Routes

To debug routing, use tools like:

  • Route Debugger: Displays all registered routes and their parameters.
  • Fiddler/Postman: Test API endpoints.

Choosing Between Routing Methods

  • Use Convention-based Routing for simple and uniform routes.
  • Use Attribute Routing for fine-grained control and complex scenarios.

These routing features in ASP.NET MVC 5 Web API provide flexibility and scalability for building robust RESTful services.

Scroll to Top