Introduction
Routing is an essential aspect of building robust and scalable web applications using ASP.NET Web API. It allows you to map incoming HTTP requests to specific actions or methods in your API controllers. This documentation will guide you through the concepts and usage of routing in ASP.NET Web API.
1. Default Routing
By default, Web API uses convention-based routing, which maps the HTTP methods and the URI templates to the corresponding action methods in the controller. The default route configuration is typically defined in the WebApiConfig.cs
file in the App_Start
folder.
Example:
csharppublic static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Default route configuration
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Explanation:
- The
MapHttpRoute
method is used to define a route in Web API. - The
name
parameter represents the name of the route. - The
routeTemplate
parameter specifies the URI pattern for the route. In this example, it is set to"api/{controller}/{id}"
. - The
defaults
parameter allows you to set default values for route parameters. In this case,id
is set as an optional parameter.
2. Attribute Routing Attribute routing provides a more flexible way to define routes by using attributes directly on the action methods or controllers. It allows you to define custom routes based on specific requirements.
Example:
csharp[RoutePrefix("api/products")]
public class ProductsController : ApiController
{
[HttpGet]
[Route("")]
public IHttpActionResult GetAllProducts()
{
// Code to get all products
// ...
}
[HttpGet]
[Route("{id:int}")]
public IHttpActionResult GetProductById(int id)
{
// Code to get product by ID
// ...
}
}
Explanation:
- The
[RoutePrefix]
attribute is used to specify a prefix for all routes defined within the controller. - The
[Route]
attribute is used to define a route for a specific action method. It can include route parameters enclosed in curly braces{}
. - In the example above, the
GetAllProducts
action method is mapped to the routeapi/products
using an empty string""
as the route template. - The
GetProductById
action method is mapped to the routeapi/products/{id}
whereid
should be an integer.
3. Route Constraints Route constraints are used to restrict the values that can be passed for a specific route parameter. They ensure that only valid values are matched to the corresponding route.
Example:
csharp[Route("api/products/{category:alpha:length(3)}")]
public IHttpActionResult GetProductsByCategory(string category)
{
// Code to get products by category
// ...
}
Explanation:
- In the example above, the route is defined with a constraint for the
category
parameter using the following route template:"api/products/{category:alpha:length(3)}"
. - The constraint
:alpha
ensures that thecategory
parameter can only contain alphabetical characters. - The constraint
:length(3)
specifies that thecategory
parameter should have a length of exactly 3 characters.
4. Route Prefixes Route prefixes allow you to define common route segments for a group of related controllers. It helps in organizing and grouping related API endpoints.
Example:
csharp[RoutePrefix("api/orders")]
public class OrdersController : ApiController
{
[HttpGet]
[Route("")]
public IHttpActionResult GetAllOrders()
{
// Code to get all orders
// ...
}
// Other action methods
// ...
}
Explanation:
- The
[RoutePrefix]
attribute is used to define a common prefix for all routes within the controller. - In the example above, the
OrdersController
is associated with the route prefix"api/orders"
. - The
GetAllOrders
action method is then mapped to the route"api/orders"
.
Conclusion Routing is a vital component of ASP.NET Web API, allowing you to handle incoming requests and map them to the appropriate action methods in your API controllers. This documentation provided an overview of default routing, attribute routing, route constraints, and route prefixes, along with code examples and explanations. Understanding and utilizing routing effectively will help you build well-structured and easily navigable Web API applications.
0 Comments