具有多个参数的 Get 在 Web api 中发生路由冲突
Route Conflicts in web api for Get with multiple parameters
我正在使用 Web Api 创建参数范围为 0 到 4 的 REST API。
以下是我的 APIs 的示例:
- GetTaxRates()
- GetTaxRatesByDate(string date, string name= "") // name 是可选参数
- GetTaxBetweenDates(string frmDate, string toDate, string name="") // name 是可选参数
- GetRecentTaxRates(string name= "") // name 是可选参数
对于这些不同的 GET 调用,
我在 webapiconfig 中创建了以下路由:
路由模板: "api/{controller}/{action}",
默认值:新{}
路由模板: "api/{controller}/{action}/{date}/{name}",
默认值:new { name= RouteParameter.Optional }
路由模板: "api/{controller}/{action}/{frmdate}/{toDate}/{name}",
默认值:new { name= RouteParameter.Optional }
当我调用 APIs 时,它对大多数路由都工作正常,但路由之间似乎存在冲突,当我调用 "No action was found on the controller 'TaxRate' that matches the request." 时出现错误动作 api/TaxRate/GetTaxBetweenDates/2015-04-01/201504-10
虽然我在使用所有参数调用相同的 api 时得到了结果:api/TaxRate/GetTaxBetweenDates/2015-04-01/201504-10/abc
当我更改路线顺序时,同样的问题发生在 GetTaxRatesbyDate API 调用。
根据 Web api 路由中的经验法则,您应该首先注册更具体的路由。看看这个 link Routing order。在这里可能有帮助的是注册更具体的路线,如“api/{controller}/GetTaxRatesByDate/{date}/{name}", defaults: new { name= RouteParameter.Optional }
我能够使用属性路由解决上述问题。
我正在使用 Web Api 创建参数范围为 0 到 4 的 REST API。 以下是我的 APIs 的示例:
- GetTaxRates()
- GetTaxRatesByDate(string date, string name= "") // name 是可选参数
- GetTaxBetweenDates(string frmDate, string toDate, string name="") // name 是可选参数
- GetRecentTaxRates(string name= "") // name 是可选参数
对于这些不同的 GET 调用, 我在 webapiconfig 中创建了以下路由:
路由模板: "api/{controller}/{action}", 默认值:新{}
路由模板: "api/{controller}/{action}/{date}/{name}", 默认值:new { name= RouteParameter.Optional }
路由模板: "api/{controller}/{action}/{frmdate}/{toDate}/{name}", 默认值:new { name= RouteParameter.Optional }
当我调用 APIs 时,它对大多数路由都工作正常,但路由之间似乎存在冲突,当我调用 "No action was found on the controller 'TaxRate' that matches the request." 时出现错误动作 api/TaxRate/GetTaxBetweenDates/2015-04-01/201504-10
虽然我在使用所有参数调用相同的 api 时得到了结果:api/TaxRate/GetTaxBetweenDates/2015-04-01/201504-10/abc
当我更改路线顺序时,同样的问题发生在 GetTaxRatesbyDate API 调用。
根据 Web api 路由中的经验法则,您应该首先注册更具体的路由。看看这个 link Routing order。在这里可能有帮助的是注册更具体的路线,如“api/{controller}/GetTaxRatesByDate/{date}/{name}", defaults: new { name= RouteParameter.Optional }
我能够使用属性路由解决上述问题。