這裏有一個路由問題以及一些誤解。
爲的WebAPI的默認路由是:
routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
這與某些約定一起:
- 的getX地圖GET方法。
- InsertX映射POST方法。
- UpdateX映射PUT方法。
- DeleteX映射DELETE方法。
當你的命名約定是不符合WepApi公約對齊,那麼你就需要指定方法,動作名稱等
同樣的,你的路線發生。如果你沒有定義其他路由,那麼只有遵循約定和默認路由的動作纔會被限制。
例如:
public IEnumerable<Carrier> GetAll(){
//this will get called when using the route: /api/carriers/
}
public IEnumerable<Carrier> Get(string id){
//this will be called when using the route: /api/carriers/1
//where 1 is the carrier id
}
將在CarrierController工作,因爲它們都與公約和路線一致。現在
,如果需要返回所有項目的一個載體的方法,你將需要這個方法:
[ActionName("getItems")]
public IEnumerable<Item> GetAllItems(string id){
//where id is the carrierid
var carrierId = id;
//because you are specifying the ActionName to getItems this will match the following route:
// /api/carriers/getItems/1
}
另一種選擇是創建上述ItemsController,並補充說,返回的項目列表的作用基於carrierId,這在概念上可能更好,但路由原則是相同的。
對象是否來自參數non-null?這可能是序列化的問題。該對象來自哪裏,它的屬性如何在GET請求中發送? – Slavo
請提供有關Carrier類別的更多信息以及GetAllItems的預期結果。它看起來應該返回某種載體細節記錄... –
是的,它可以做到,但你可能應該閱讀以下帖子,然後再決定這樣做:http://stackoverflow.com/questions/11091160/rest- api-get-request-with-body和http://stackoverflow.com/questions/978061/http-get-with-request-body –