【问题标题】:WebAPI how to specify which route a controller will be reachedWebAPI如何指定控制器将到达哪个路由
【发布时间】:2013-11-03 10:30:41
【问题描述】:

我一直在试验 MVC WebAPI,非常酷的东西。但我在路线的概念上苦苦挣扎。

作为一个例子,我有一个类似于以下的 webAPI 项目结构:

项目:

  • 控制器
    • 客户
      • CustomerController.cs
      • CustomerAddressController.cs
    • 产品
      • ProductCategoriesController.cs
      • 产品控制器

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

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

当我只有与客户相关的控制器时,这很好用。 所以我可以打电话:

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

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

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

我想要:

  • 获取 api/products/?prodID= 5678

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

  • GET api/products/categories/?catID= 1357

我以为我要做的就是添加更多路由,但我找不到如何将各种控制器与我希望它们的路由相关联?

如果我添加了另一个路由,我最终会得到两个不同的 uri 路由到我构建的每个控制器。

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

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing


    【解决方案1】:

    使用 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)
        {
            // ...
        }
    }
    

    【讨论】:

    • 完美:我一直在读到 WebAPI 删除了方法装饰,如果这是真的,我很高兴看到它回来。谢谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2013-04-22
    • 2021-09-20
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2012-09-15
    相关资源
    最近更新 更多