1

我希望能夠通過不同的id類型標識資源。例如:asp.net webapi url來標識相同的資源

GET http://example.com/customers/internalId=34

public Customer GetByInternalId(int internalId){...} 

和 GET http://example.com/customers/externalId= 'JOHNDOE' 去

public Customer GetByExternalId(string externalId){...} 

我知道我可以通過一個通用的有一些分析邏輯做到這一點控制器方法,但我不想這樣做。如果可以的話,如何使用asp.net webapi的路由功能來實現這一點。

回答

0

你的方法沒有什麼意義,爲什麼你會以Get ....開頭的方法返回void?

而且,這些路線:

http://example.com/customers/internalId=34 
http://example.com/customers/externalId='JohnDoe 

從MVC /網頁API的角度無效。這是它們應該如何的樣子:

http://example.com/customers?internalId=34 
http://example.com/customers?externalId=John 

默認的Web API路由應區分兩者並將其路由到不同的操作。

編輯:

創建下面的模板作用:

[HttpGet] 
public string InternalId(int id) 
{ 
    return id.ToString(); 
} 

定義路由的Web API:

config.Routes.MapHttpRoute(
     name: "Weird", 
     routeTemplate: "{controller}/{action}={id}", 
     defaults: new { id = RouteParameter.Optional } 
     ); 

這允許你寫:

http://localhost:7027/values/internalId=12 

試試吧......

然後,你可以添加另一種方法:

[HttpGet] 
public string ExternalId(string id) 
{ 
    return id; 
} 

這:

http://localhost:7027/values/externalId=bob 

也能發揮作用。

顯然,我的控制器的名稱是ValuesController,因爲我剛剛使用默認的Web Api模板測試了這一點。

+0

感謝您指出方法中的錯誤。雖然我意識到查詢字符串可以工作,但這不是我正在尋找的。我想做些什麼鏈接在這裏完成:https://developer.linkedin.com/documents/profile-api, http://api.linkedin.com/v1/people/id=abcdefg, http: //api.linkedin。com/v1/people/url = darthjit 2013-03-19 13:44:41

+0

我已經更新了我的帖子,告訴你如何做你想做的事情。如果你密切關注我所定義的路線,我相信你會明白。 – 2013-03-19 14:10:23

1

我建議你儘量避免做你的建議。爲相同的資源創建兩個不同的URI將使得使用緩存變得更加困難。相反,我會建議使用一個URL重定向到另一個。

例如

> GET /customers/34 
< 200 OK 


> GET /Customers?name=JohnDoe 
< 303 See Other 
< Location: http://example.com/customers/34 
+0

謝謝達倫。我以前見過這個答案。我正在嘗試做什麼鏈接在這裏:https://developer.linkedin.com/documents/profile-api,並想知道這種路由是否可能與WebApi。 – darthjit 2013-03-19 13:41:51

+0

@darthjit肯定可以使用WebAPI,因爲您可以替換路由組件並自己實現它。無論現有的路由機制能否實現,我都不知道,因爲我永遠不會試圖做這樣的事情。使用代字號返回「當前配置文件」對於Linked in來說是一件特別愚蠢的事情。 – 2013-03-19 14:08:49