【问题标题】:How 2 WebAPI Routing can accept same type parameter2 WebAPI 路由如何接受相同类型的参数
【发布时间】:2016-05-12 00:19:04
【问题描述】:

我有一个包含多种方法的 Web Api。我的路由有问题。我有一种方法是通过yearId 返回产品,另一种方法是通过product id 返回产品。这是我想出的两条路线:

   /api/records/products?yearId=10

   /api/records/products/15

这是我的两种方法:

    [HttpGet]
    [Route("getbyyearid")]
    public async Task<Product> GetByYearid(int yearId)
    {
          .....     
    }


    [HttpGet]
    [Route("getbyid")]
    public async Task<IEnumerable<Product>> GetByid(int productId)
    {
        ......
    }

我应该有什么路由映射,以便我可以使用这 2 条路由访问我的 Web API:

    /api/records/products?yearId=10

    /api/records/products/15

【问题讨论】:

    标签: c# asp.net-web-api asp.net-web-api-routing


    【解决方案1】:

    您可以考虑使用 Attribute Routing 来自定义您希望如何使用路由。

    这是一个示例,说明如何实现您想要的路线:

    [RoutePrefix("api/records")]
    public class RecordsController: ApiController {
        // GET api/records/products?yearid=10    
        [HttpGet]
        [Route("products")]
        public async Task<Product> GetByYearid(int yearId) {
              .....     
        }
    
        // GET api/records/products/15
        [HttpGet]
        [Route("products/{productId:int}")]
        public async Task<IEnumerable<Product>> GetByid(int productId) {
            ......
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-13
      • 2017-07-21
      • 2015-08-18
      • 2020-04-26
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多