2016-08-02 33 views
2

我需要同時支持基於查詢參數的路由(/api/models?id=1)和基於路由的路由(/api/models/1),同時仍允許明確訪問模型集合(/api/models)?我該如何同時綁定FromQuery和FromRoute參數?

我的長相控制器(東西)是這樣的:

[Route("/api/{controller}")] 
public class ModelsController : Controller 
{ 
    [HttpGet] 
    public Models[] GetModels([FromQuery]QueryOptions queryOptions) 
    { 
     //... 
    }  

    [HttpGet("{id:int}")] 
    public Model Get([FromRoute] int id) 
    { 
     //... 
    } 

    [HttpGet("?{id:int}")] 
    public Model Get2Try1([FromQuery] int id) 
    { 
     //Fails with ": The literal section '?' is invalid. 
     //Literal sections cannot contain the '?' character." 
     //Which makes sense after some reading... 
    } 

    [HttpGet] 
    public Model Get2Try2([FromQuery] int id) 
    { 
     //Fails with "AmbiguousActionException: Multiple actions matched. 
     //The following actions matched route data and had all constraints satisfied: 
     //GetModels and Get2Try2" 
     //Which I think I understand as well...the absence of optional params 
     //means ambiguous routing... 
    } 

    [HttpGet] //What here? 
    public Model Get2Try3([FromQuery] int id) //and/or here? 
    { 

    } 
} 

我覺得應該有一些辦法(有聲明路由)做到這一點。有沒有人做過這些事情?

另外,當前的代碼庫是ASP.NET Core(RC1),很快就會升級到RTM/1.0。任何一方的細節可能都是相似的,但我對兩者都有興趣。

回答

3

我發現了以下工作:

[HttpGet, Route("{id?}")] 

...關鍵是主要的 '?'。您不需要方法簽名中的任何[FromX],這可以實現查詢字符串和路由參數傳遞。

不幸的是揚鞭UI不喜歡它,並希望一些明確的參數,開箱(https://github.com/domaindrivendev/Ahoy/issues/47https://github.com/domaindrivendev/Ahoy/issues/182)的,但這是另一個故事:)

+0

這並不爲我工作。它起[FromRoute]的作用,不起[FromQuery] – neeohw