3 April 2017
Routing is a key concept in web development, especially when building Web APIs. In .NET Core, routing is used to map HTTP requests to the appropriate controller actions or methods in your application. This allows you to define how requests are handled, which URLs are accessible, and what data can be returned in response. In this post, we’ll take a look at the basics of routing in .NET Core, including routing templates, query parameters, and constraints.
1. What Is Routing in .NET Core?
Routing in .NET Core is the mechanism that matches incoming HTTP requests to actions in your controllers. When a request is made to your application, .NET Core uses routing to figure out which controller and action method should handle the request based on the request’s URL and HTTP method.
For example, a GET request to /api/products/5
might be routed to the GetProductById
action in the ProductsController
, passing the ID 5
as a parameter.
2. Routing Templates
A routing template is a pattern that defines the structure of the URL for a particular route. In .NET Core, routing templates can include variables (also called route parameters) that are matched from the incoming URL.
A simple route template could look like this:
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
// GET api/products/5
[HttpGet("{id}")]
public IActionResult GetProductById(int id)
{
var product = _productService.GetProductById(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
In the above example, the route api/products/{id}
contains a route parameter id
, which corresponds to a variable in the URL. When the user visits api/products/5
, the route template will match the value 5
to the id
parameter in the GetProductById
method.
Here’s a breakdown of the routing template components:
api/[controller]
: This is a route prefix that points to the controller.[controller]
is a token that gets replaced with the name of the controller (without the “Controller” suffix).{id}
: This is a route parameter that can match any value in the URL. It is mapped to the method parameterid
.
3. Route Constraints
In .NET Core, you can also apply constraints to route parameters. Constraints allow you to restrict the kind of data that can be passed as a parameter. For example, you can ensure that a route parameter is a number or a specific string pattern.
Here’s an example of a route with a constraint on the id
parameter to ensure it must be a number:
[HttpGet("{id:int}")]
public IActionResult GetProductById(int id)
{
var product = _productService.GetProductById(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
In this case, the route will only match if id
is an integer (int
). If a user attempts to access api/products/abc
, the request will not match the route because abc
is not a valid integer.
Common Route Constraints in .NET Core:
int
: Ensures the route parameter is an integer.bool
: Ensures the route parameter is a boolean (true
orfalse
).datetime
: Ensures the route parameter is a validDateTime
.minlength
/maxlength
: Used for string length validation.
4. Query Parameters
In addition to route parameters, query parameters are another way to pass data in the URL. These are typically used for optional data or filters. Query parameters come after the question mark (?
) in a URL, and are usually in the form of key=value
.
For example:
GET /api/products?category=electronics&sort=price
In this example, the query parameters are category
and sort
. You can access query parameters in your action method using the [FromQuery]
attribute.
Here’s an example of how to use query parameters in a Web API controller:
[HttpGet]
public IActionResult GetProducts([FromQuery] string category, [FromQuery] string sort)
{
var products = _productService.GetProducts(category, sort);
return Ok(products);
}
The category
and sort
parameters will be extracted from the query string, and you can use them to modify the results that your API returns.
5. Combining Route Parameters and Query Parameters
Sometimes you need to combine both route parameters and query parameters in the same route. Here’s an example:
GET /api/products/5?category=electronics&sort=price
In this case, the 5
is a route parameter, and the query parameters category
and sort
are included in the URL. Here’s how you can define a route to handle this:
[HttpGet("{id}")]
public IActionResult GetProductById(int id, [FromQuery] string category, [FromQuery] string sort)
{
var product = _productService.GetProductById(id, category, sort);
return Ok(product);
}
6. Conclusion
In this post, we’ve explored the basics of routing in .NET Core, including:
- Routing templates and how to define routes in controllers.
- Route parameters and how to pass dynamic data in the URL.
- Route constraints to limit the type of data passed in the URL.
- How to handle query parameters to filter and modify requests.
Routing is a powerful feature of .NET Core that allows you to build flexible and RESTful Web APIs. By mastering routing and understanding how to create clean and readable URLs, you can create efficient APIs and enhance the overall user experience.
Happy coding!