0

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.

4

3 回答 3

2

我们通常遵循来自 apigee 的 Web API 设计指南,它是在全球多个成功的 Web API 中使用的模式集合。

该指南建议使用下面的图表来组织您的 web api 资源,理想的情况是按资源仅保留 2 个基本 url:

在此处输入图像描述

在您的具体情况下,您的资源是“产品”,所以我建议您使用以下网址:

  • /产品
  • /产品/{id}
  • /products?cagetoryName={categoryName}

你的 web api 表路由可以很容易地配置,比如:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new
    {
        id = RouteParameter.Optional,
        action = RouteParameter.Optional
    });
于 2013-05-09T15:19:11.323 回答
2

我假设一个类别可能会返回多个产品。

在 VB 中使用可选参数,例如:

Public Function GetProducts(Optional category As String = "") As IEnumerable(Of Product)
Public Function GetProduct(ByVal id as Integer) As Product

或 C#

public IEnumerable<Product> GetProducts(string category = "")
public Product GetProduct(int id)

使用 URL 之类的:

/api/product
/api/product/1
/api/product?category=myCategory

保留默认路由。

于 2013-05-09T20:16:52.967 回答
1

最后我有解决方案。我正在寻找可以根据参数类型调用方法的路由配置。

       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"})

缺少的链接在第一条路由上使用了约束,指定它只接受数字值。例如 api/products/1 第二个配置处理剩余的请求,例如在 url 中为 categoryname 指定的字符串值,例如 api/products/books 第三个配置路由到所有没有参数的请求到操作方法

使用正确的参数名称路由模板也很重要,例如 prodid,categoryname 。该名称应与相应操作方法中声明的名称相同。

于 2013-05-10T15:10:56.643 回答