2013-10-24 97 views
3

我一直在試驗MVC WebAPI,非常酷的東西。但我正在努力應付路線的概念。WebAPI如何指定控制器將被達到的路線

作爲一個例子,我有一個的WebAPI項目結構類似如下:

項目:

  • 控制器
    • 客戶
      • CustomerController.cs
      • CustomerAddressController.cs
    • 產品
      • ProductCategoriesController.cs
      • 的ProductsController

目前,我有一個API定義路由在WebApiConfig.cs

 config.Routes.MapHttpRoute(
      name: "CustomerApi", 
      routeTemplate: "api/customer/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 

釷當我只有客戶相關的控制器時工作正常。 所以我可以打電話:

  • 獲取API /客戶/ CustomerAddress /的customerID = 1234

,但現在,我已經加入了與產品相關的控制器我找到的配置是(當然)獲得產品我有打電話給烏里?

  • 獲取API /客戶/產品/ PRODID = 5678 *但我不希望這個開放的

,而不是我想:

  • 獲取API /產品/ PRODID = 5678

和產品類別,我想一個類似於:

  • 獲取API /產品/類別/?catID = 1357

我想我所要做的就是添加更多的路線,但我無法找到如何關聯variou我想要他們的路線的控制器?

如果我添加了另一條路由,我最終得到了兩個不同的uri路由到我構建的每個控制器。

我該如何實現我所希望的邏輯分區?

回答

6

使用Web Api 2,您可以平滑地爲您的操作定義特定的路由。例如:

public class CustomerController : ApiController 
{ 
    [Route("api/customer")] 
    public IEnumerable<Customer> GetCustomers() 
    { 
     // .. 
    } 

    [Route("api/customer/{customerID}")] 
    public Customer GetCustomer(int customerID) 
    { 
     // .. 
    } 

    [Route("api/customer/CustomerAddresses/{customerID}")] 
    public Address GetCustomerAddresses(int customerID) 
    { 
     // ... 
    } 
} 

public class ProductController : ApiController 
{ 
    [Route("api/product")] 
    public IEnumerable<Product> GetProducts() 
    { 
     // .. 
    } 

    [Route("api/product/{prodID}")] 
    public Product GetProduct(int prodID) 
    { 
     // .. 
    } 

    [Route("api/product/categories/{catID}")] 
    public Category GetCategory(int catID) 
    { 
     // ... 
    } 
} 
+0

完美:我一直在閱讀WebAPI已經刪除方法裝飾,如果這是真的,我很高興看到它回來。 謝謝你的回答。 – John