Reputation: 159
I am trying to find the routing configuration for apicontroller having multiple get methods.
The controller class has 3 methods:
Public Function GetAllProducts() As IEnumerable(Of Product)
Public Function GetProductById(prodid As Integer) As Product
Public Function GetProductByCategory(categoryName As String) As Product
Please suggest the routing configuration needed for all the 3 methods.
Upvotes: 0
Views: 2186
Reputation: 159
Finally I have the solution. I was looking for routing configuration which can call the methods depending on the parameter type .
config.Routes.MapHttpRoute( _
name:="apiById", _
routeTemplate:="api/{controller}/{prodid}", _
defaults:=New With {.controller = "Products"}, constraints:=New With {.prodid
= "^\d+$"})
config.Routes.MapHttpRoute( _
name:="apiByname", _
routeTemplate:="api/{controller}/{categoryName}", _
defaults:=New With {.controller = "Products"})
config.Routes.MapHttpRoute( _
name:="apiByAction", _
routeTemplate:="api/Products", _
defaults:=New With {.controller = "Products"})
The missing link was using the constraint on the first route specifying it to accept number values only. e.g. api/products/1 The second configuration handles the remaining requests like string values specified in the url for categoryname e.g api/products/books The third configuration routes to all the request to action method having no parameters
Also its important to use the correct parameter name routetemplate like prodid,categoryname . The name should be same as declared in the corresponding action method.
Upvotes: 1
Reputation: 336
I assume that a category may return several products.
In VB use optional parameters like:
Public Function GetProducts(Optional category As String = "") As IEnumerable(Of Product)
Public Function GetProduct(ByVal id as Integer) As Product
or C#
public IEnumerable<Product> GetProducts(string category = "")
public Product GetProduct(int id)
Use URL´s like:
/api/product
/api/product/1
/api/product?category=myCategory
Leave the default route in place.
Upvotes: 2
Reputation: 7407
We usually to follow the Web API Design Guidelines from apigee, that are collections of patterns used in several and succesful Web APIs around the world.
The guideline suggest the chart bellow to organize your web api resources, the ideal scenario is keep just 2 base urls by resource:
In your specific case, your resource is "Product", so I suggest to you the bellow urls:
And your web api table routes can be configurated very easy, like:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new
{
id = RouteParameter.Optional,
action = RouteParameter.Optional
});
Upvotes: 2