我用選定的答案從這裏:Routing based on query string parameter name建立我的路線,但預期他們不工作:的WebAPI路由問題 - 無法路由到需要採取行動
我的路線:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}",
defaults: new { controller = "Products" }
);
我的行動:
public string GetProductById(int id) {}
public string GetProductByIsbn(string isbn) {}
我試圖通過調用這些:
localhost:60819/api/products/id=33 //doesn't work
localhost:60819/api/products/33 //does work
和
http://localhost:60819/api/products/isbn=9781408845240 //doesn't work
http://localhost:60819/api/products/testString //test with a definite string - doesn't work - still tries to use GetProductById(int id)
錯誤是兩個不工作一樣:
<Error><Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String GetProductById(Int32)' in 'BB_WebApi.Controllers.ProductsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
似乎認爲該ID沒有被傳遞......?
我已經閱讀了所有的msdn文檔,但我似乎在某處丟失了某些東西。任何人都可以看到我要去哪裏嗎?
謝謝,你是正確的,那個例子沒有工作,我有另一個路由:'routeTemplate:「api/{controller}/{id}/{anotherid}」,'它允許它工作 - 我didn不要以爲它有2個參數,但它們都是可選的,所以它顯然會工作! 在問題中使用路由和'http:// localhost:60819/api/products?isbn = 9781408845240'我得到錯誤'沒有爲這個對象定義的無參數構造函數.'我假設是指我的ProductsController? – Rick
除非你正在實現一個自定義的控制器激活器(例如,因爲你包括一個DI框架bottstrapper,就像http://stackoverflow.com/questions/13018417/is-there-any-httpcontrollerbuilder-for-asp-net- web-api)控制器激活器需要無參數構造函數來創建控制器的實例。 – JotaBe