2017-10-11 31 views
2

我們使用.NET Core構建Web API。我們需要支持「GetBy」功能,例如GetByName,GetByType等,但我們遇到的問題是如何通過以Restful方式進行的路線描述以及方法重載不能正確處理我們認爲路線應該如何。我們使用的是MongoDB,所以我們的ID是字符串。Web API中的「GetBy」方法

我假設我們的路線應該是這樣的:

/api/templates?id=1 
/api/templates?name=ScienceProject 
/api/templates?type=Project 

而問題是,我們在我們的控制器的所有方法都有一個字符串參數,並沒有正確映射。我的路線應該不同還是有辦法將這些路線正確映射到適當的方法?

回答

4

如果參數是互斥的,即只通過名稱或類型進行搜索,但沒有按名稱和類型,那麼你可以有參數是路徑,而不是查詢,則params的一部分。

[Route("templates")] 
public class TemplatesController : Controller 
{ 
    [HttpGet("byname/{name}")] 
    public IActionResult GetByName(string name) 
    { 
     return Ok("ByName"); 
    } 

    [HttpGet("bytype/{type}")] 
    public IActionResult GetByType(string type) 
    { 
     return Ok("ByType"); 
    } 
} 

這個例子會導致類似的路線:如果參數不是相互eclusive那麼你應該做這樣的answer by Fabian H.

建議

/api/templates/byname/ScienceProject 
/api/templates/bytype/Project 

1

您可以使用單個get方法創建一個TemplatesController,該方法可以接受所有參數。

[Route("api/templates")] 
public class TemplatesController : Controller 
{ 
    [HttpGet] 
    public IActionResult Get(int? id = null, string name = null, string type = null) 
    { 
     // now handle you db stuff, you can check if your id, name, type is null and handle the query accordingly 
     return Ok(queryResult); 
    } 
}