How to define routing in a .NET Core API?
Ask by Steilla Mitchel
Updated 29 Aug 2023
Routing in a .NET Core API is the process of mapping HTTP requests to action methods in controllers. It is used to define how users can access your API.
There are two ways to define routing in a .NET Core API:
Here is an example of attribute routing in a .NET Core API:
C#
In this example, the
GetProducts()action method is mapped to the/productsendpoint because it has theHttpGetattribute. TheCreateProduct()action method is mapped to the/productsendpoint because it has theHttpPostattribute.Here is an example of conventional routing in a .NET Core API:
C#
In this example, the
GetProducts()action method is mapped to the/productsendpoint because its method name matches the route name. TheCreateProduct()action method is mapped to the/productsendpoint because its method name matches the route name and the HTTP verb isPOST.Here are some additional tips for defining routing in a .NET Core API:
RoutePrefixattribute to group related routes together. This will help to keep your URLs organized and easy to understand.ApiVersionattribute to specify the API version for each route. This will help to ensure that your API is backward compatible.