【问题标题】:Attribute Routing Constrict Route属性路由 限制路由
【发布时间】:2013-05-16 13:04:27
【问题描述】:

我正在为 WebApi 使用 http://attributerouting.net/ nuget 包。这是我的两个 GET 方法和路由属性,用于列表和特定项目:

[GET("api/products/{tenantid}/{channelid}?{skip=0}&{take=20}&{status=1}")]
public IEnumerable<Product> Get(short tenantId, byte channelId, int status, int skip, int take)

[GET("api/products/{tenantid}/{channelid}/{id}")]
public Story Get(short tenantId, byte channelId, long id)

但在生成的帮助 URI 中,显示了三个 GET 选项。

GET api/products/{tenantid}/{channelid}?status={status}&skip={skip}&take={take} 
GET api/products/{tenantid}/{channelid}?id={id} 
GET api/products/{tenantid}/{channelid}/{id}

即使“id”不是第一个 GET 方法的参数。如何消除末尾带有“?id = {id}”的中间URI?我想我需要某种约束,但我无法从文档站点中弄清楚。

【问题讨论】:

    标签: asp.net-web-api attributerouting asp.net-mvc-apiexplorer


    【解决方案1】:
    1. 要解决此问题,您可以以不同的方式命名操作。示例:GetAllProducts、GetProduct

    2. 您看到的问题是一种预期行为,因为 ApiExplorer(HelpPage 使用)会访问路由集合中的所有路由,并且它会检查每个路由以查看可以从该路由执行哪些操作。现在使用上面的属性修饰路由,路由集合中的路由很可能如下所示:

    一个。 "api/products/{tenantid}/{channelid}", controller="Products", action = "Get" 等等...

    b. "api/products/{tenantid}/{channelid}/{id}", controller="Products", action = "Get"...

    现在对于路线“a.”,ApiExplorer 检查可以到达哪些操作,并注意到对于控制器“产品”和操作“获取”,可以到达 2 个操作,并且它还尝试查看如何许多参数来自路由路径本身,如果操作中有任何参数不是来自路由路径,它假定它来自查询字符串......因此您看到“?id = {ID}”。希望这会有所帮助。

    【讨论】:

    • 修复了它。我什至没有考虑更改方法名称。当切换到备用路由技术时,我应该认识到方法名称不是路由约定的一部分。
    猜你喜欢
    • 2013-06-07
    • 2021-09-04
    • 2023-03-26
    • 2017-03-24
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    相关资源
    最近更新 更多