web-api
  1. web-api-applying-routing-constraints

Applying Routing Constraints - (Web API Attribute Routing)

Web API Attribute Routing allows you to define routing constraints that restrict the input to actions. Constraints are used to filter out invalid routes and are helpful in scenarios where actions should only be invoked if the parameter matches specific criteria. This page explains how to apply routing constraints in Web API Attribute Routing.

Syntax

To apply routing constraints in Web API Attribute Routing, you need to specify the constraint as an attribute on the target method or parameter. Here is an example of applying a constraint to a route parameter:

[HttpGet("product/{id:int}")]
public IActionResult GetProduct(int id)
{
    // code to retrieve product
}

Example

Here is an example of how to apply a routing constraint to a parameter in a Web API Attribute Routing action:

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly List<Product> _products = new List<Product>
    {
        new Product { Id = 1, Name = "Product 1", Price = 9.99M },
        new Product { Id = 2, Name = "Product 2", Price = 19.99M },
        new Product { Id = 3, Name = "Product 3", Price = 29.99M }
    };

    [HttpGet("product/{id:int}")]
    public IActionResult GetProduct(int id)
    {
        var product = _products.FirstOrDefault(p => p.Id == id);

        if (product == null)
        {
            return NotFound();
        }

        return Ok(product);
    }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

The GetProduct method has a constraint on the id parameter to ensure that only integer values are accepted for the route parameter.

Output

When you invoke the GetProduct action with an integer value for the id parameter, you will receive a JSON result containing the product information. If the value of the id parameter is not an integer or not found in the _products list, the GetProduct action will return a NotFound result.

Explanation

In the example, the GetProduct method accepts an integer parameter id that matches the constraint `

Published on: