WebAPI如何指定将到达控制器的路由

Joh*_*ohn 3 asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing

我一直在尝试使用MVC WebAPI,非常酷的东西.但我正在努力解决路线问题.

作为一个例子,我有一个webAPI项目结构,如下所示:

项目:

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

目前我在WebApiConfig.cs中定义了一个API路由

        config.Routes.MapHttpRoute(
            name: "CustomerApi",
            routeTemplate: "api/customer/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
Run Code Online (Sandbox Code Playgroud)

当我只有客户相关的控制器时,这工作正常.所以我可以打电话:

  • GET api/customer/CustomerAddress /?customerID = 1234

但是现在我已经添加了与配置相关的产品相关控制器(当然)以获得我必须调用Uri的产品:

  • GET api/customer/products /?prodID = 5678*但我不想要这个Uri

相反,我想:

  • 获取api/products /?prodID = 5678

对于产品类别,我想要类似于:

  • 获取api /产品/类别/?catID = 1357

我认为我必须做的就是添加更多路线,但是我无法找到如何将各种控制器与我希望的路线联系起来?

如果我确实添加了另一条路线,我最终会将两条不同的uri路由到我建立的每个控制器.

如何实现我想要的逻辑分区?

Réd*_*tar 7

使用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)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)