2017-09-29 58 views
0

我嘗試了其他類似問題的答案,但我仍然遇到此問題。 我們正在實施一個ASP.NET REST API與類似下面的設置:當Id是字符串時,路由到多個GETS失敗

[Authorize] 
[Route("api/cars/{id:int}")] 
public HttpResponseMessage Get(int id) 
{ 
    //Some stuff 
} 

[Authorize] 
[Route("api/cars/{brand?}/{color?}")] 
public HttpResponseMessage GetBySource(string brand = null, string color = null) 
{ 
    //Some stuff 
} 

路由很好,謝謝工程的INT約束的Get(INT ID)方法,它支持電話爲:

{host}/api/cars/1 
{host}/api/cars/toyota 
{host}/api/cars/toyota/blue 
{host}/api/cars?brand=toyota&color=blue 

現在有一個新的要求,以支持字符串ID 下面的「邏輯」的變化(以消除該ID的INT約束)已經打破了設置:

[Authorize] 
[Route("api/cars/{id}")] 
public HttpResponseMessage Get(string id) 
{ 
    //Some stuff 
} 

現在大多數以前調用路由獲取(字符串ID):

{host}/api/cars/1    //---> Works OK 
{host}/api/cars/toyota  //---> "toyota" is the car Id instead of brand (No OK) 
{host}/api/cars?brand=toyota //---> "brand=toyota" is the car Id instead of parsing the brand (No OK) 
{host}/api/cars/toyota/blue //---> (404 Error) 
{host}/api/cars?brand=toyota&color=blue //---> (404 Error) 

它的意義畢竟。 [Route(「api/cars/{id}」)]將汽車後面的任何字符串視爲Id,並期待[Route(「api/cars/{id}/xxx/{yyy}」) ]以適應其他請求。但是將一個獨特的Id放在其他過濾器之前是沒有意義的。

我們正在評估只有在真正需要時才更改我們以前的設計。所以我的問題是:我們 可以做如下的設計工作?:

{host}/api/cars/A100T50 
{host}/api/cars/toyota 
{host}/api/cars/toyota/blue 
{host}/api/cars?brand=toyota&color=blue 

如果不是這樣,它的設計你會建議我使用?

我的路線是配置簡單:

public static void Register(HttpConfiguration config) 
{ 
    config.MapHttpAttributeRoutes(); 
} 

預先感謝任何指導

回答

1

您能夠將兩種方法結合起來?

[Authorize] 
//edit: add another route so that it recognizes id 
[Route("api/cars/{id}")] 
[Route("api/cars")] 
public HttpResponseMessage Get(string brand = "", string color = "", string id = "") 
{ 
    //example to get from database based on whichever parameter provided 
    using(var ctx = new DbContext()) 
    { 
     var cars = ctx.Cars 
         .Where(car => String.IsNullOrEmpty(id) || car.Id == id 
         && String.IsNullOrEmpty(color) || car.Color == color 
         && String.IsNullOrEmpty(brand) || car.Brand == brand); 
    //Some stuff 
} 

的你能夠調用

{host}/api/cars/AT100 
{host}/api/cars?id=AT100 
{host}/api/cars?color=black 
+0

它將工作,但我也應該保持這樣的工作:(東道國)/ API /汽車/ AT100。也許重新排序參數將是好的 – zameb

+1

重新排序不會有幫助,但您可以定義多個路線。所以[Route(「api/cars/{id}」]將會這樣做。 –

+0

我編輯了我的答案,我希望它能正常工作。 –