2015-06-01 22 views
1

我用選定的答案從這裏: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文檔,但我似乎在某處丟失了某些東西。任何人都可以看到我要去哪裏嗎?

回答

2

你有幾個錯誤(你沒有顯示所有相關的代碼,或者你顯示了錯誤的代碼,如下面解釋的,與路徑模板中的id有關)。

localhost:60819/api/products/id=33 //doesn't work 

這絕對不行。如果你想傳遞的,而不是/id=33命名參數的URL必須使用的查詢字符串,即,你需要使用?id=33

localhost:60819/api/products/33 //does work 

有了您展示的路線,這可不行。只有在tyour route模板中定義這些參數時,才能將參數作爲URL段傳遞。您的路線模板應該如下所示:api/{controller}/{id},以便可以從網址中恢復id,並且此第二個網址確實有效。

http://localhost:60819/api/products/isbn=9781408845240 

與第二個相同。使用?isbn=9781408845240

http://localhost:60819/api/products/testString 

這只是testString映射到路徑模板的參數。你需要這樣的東西:isbn=textString能夠調用你感興趣的動作。

所以,請記住這一點:

  • 命名參數必須在URL查詢字符串傳遞,使用正確的查詢字符串的語法,這是這樣的:?param1=val1&param2=val2
  • 網址段參數必須在路由模板存在。如果沒有,活頁夾可能對它們做任何事情都是不可能的。

由於看起來您缺少大量信息,請閱讀此文檔:Parameter Binding in ASP.NET Web API

這對你也很有趣:Attribute Routing in ASP.NET Web API 2,它允許你使用比路由模板更靈活的路由屬性。

+0

謝謝,你是正確的,那個例子沒有工作,我有另一個路由:'routeTemplate:「api/{controller}/{id}/{anotherid}」,'它允許它工作 - 我didn不要以爲它有2個參數,但它們都是可選的,所以它顯然會工作! 在問題中使用路由和'http:// localhost:60819/api/products?isbn = 9781408845240'我得到錯誤'沒有爲這個對象定義的無參數構造函數.'我假設是指我的ProductsController? – Rick

+0

除非你正在實現一個自定義的控制器激活器(例如,因爲你包括一個DI框架bottstrapper,就像http://stackoverflow.com/questions/13018417/is-there-any-httpcontrollerbuilder-for-asp-net- web-api)控制器激活器需要無參數構造函數來創建控制器的實例。 – JotaBe