15 Mar 2024




Intermediate

Routing in ASP.NET Core WebAPI determines how incoming HTTP requests are mapped to the respective controller action methods. It's essentially the process of matching the URL of an incoming request to the appropriate endpoint in your application.

Here's a breakdown of how routing works in ASP.NET Core WebAPI:

  1. Routing Middleware: Routing in ASP.NET Core is handled by the routing middleware, which is included in the middleware pipeline of your application. This middleware examines incoming HTTP requests and attempts to match them to registered routes.

  2. Route Definitions: Routes are defined using the MapRoute extension method within the Startup.Configure method. This method typically resides in the Startup.cs file of your application. Routes are defined using a combination of URL patterns and route templates.

  3. Route Templates: Route templates define the structure of the URL that the routing system should match. They can include placeholders for parameters, which are then passed to the corresponding action method as arguments. For example, a route template might look like /api/{controller}/{id} where {controller} and {id} are placeholders for dynamic values.

  4. Controller Actions: Controller actions are methods within your controller classes that handle incoming requests. Each action method is annotated with HTTP method attributes like [HttpGet], [HttpPost], [HttpPut], [HttpDelete], etc., to specify the HTTP verb it should respond to.

  5. Route Matching: When an incoming request is received, the routing middleware matches the URL of the request to the registered route templates. It then selects the route with the best match based on the URL and invokes the corresponding action method.

  6. Route Parameters: Route parameters are extracted from the URL based on the placeholders defined in the route template. These parameters are then passed to the corresponding action method as arguments. For example, in the route template /api/{controller}/{id}, controller and id are parameters that are extracted from the URL.

  7. Attribute Routing: In addition to convention-based routing, ASP.NET Core also supports attribute routing, where routes are defined directly on the controller and action methods using attributes like [Route]. Attribute routing provides more control over the routing behavior and allows for more expressive route definitions.

Here's an example of how routing is typically configured in ASP.NET Core WebAPI:

// Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

And an example of a controller with route templates:

// ExampleController.cs

[ApiController]
[Route("api/[controller]")]
public class ExampleController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult Get(int id)
    {
        // Implementation for GET /api/example/{id}
    }

    [HttpPost]
    public IActionResult Post([FromBody] ExampleModel model)
    {
        // Implementation for POST /api/example
    }
}

In this example, the HttpGet attribute specifies that the Get method should handle GET requests to /api/example/{id}, and the HttpPost attribute specifies that the Post method should handle POST requests to /api/example.