2017-08-20 18 views
-1

私はASP.Net Web API Routingについて簡単な質問をしています。私は、次のコントローラいる:基本的な従来のルーティングasp.net webapi

public class CustomersController: ApiController 
{ 
    public List<SomeClass> Get(string searchTerm) 
    { 
     if(String.IsNullOrEmpty(searchTerm)) 
     { 
      //return complete List 
     } 
     else 
     { 
      //return list.where (Customer name contains searchTerm) 
     } 
    } 
} 

私のルーティング設定(従来の)次のようになります。私は、URLをヒットした場合

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

config.Routes.MapHttpRoute(name:"CustomersApi", 
routeTemplate:"api/{controller}/{searchTerm}" 
defaults:new {searchTerm = RouteParameter.Optional}); 

http://localhost:57169/api/Customers/Vi 私は404-ないの取得は

を見つけました私がルートの順序を逆にすると、それは動作します。 質問が最初のケースでは、最初のルート(DefaultApi)と一致していますか?そうでない場合、なぜ2番目のルートを試していないのですか? stringだからあなたのURLは、このテンプレートを尊重し、このルートが選択されているなどint、:Idは任意の型を指定できますので

答えて

0

このルートテンプレート

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

はあなたのURLと一致します。このテンプレートは、よりrestrcitive作り、あなたが「Idパラメータは、このテンプレートの数値型でなければなりません」のような何かを言うことによって、それにいくつかの制約を追加する必要があり、次のテンプレートに移動するにはASP.NetのWeb APIを作るために

。だから、以下のようなconstraintsのパラメータを追加します。

config.Routes.MapHttpRoute(name:"DefaultApi", 
    routeTemplate: "api/{controller}/{id}", 
    defaults: new {id = RouteParameter.Required}, // <- also here I put Required to make sure that when your user doesn't give searchTerm so this template will not be chosen. 
    constraints: new {id = @"\d+"} // <- regular expression is used to say that id must be numeric value for this template. 
); 

をしたがって、上記のテンプレートはスキップされ、次が選択されますhttp://localhost:57169/api/Customers/ViこのURLを使用することによって。

+0

このルートが選択された場合、なぜコントローラメソッドがトリガされないのですか? Controllerメソッドのパラメータ名がidではなくsearchTermなので、それですか? – Vikas

+0

これは選択されましたが、 "id"をパラメータとするアクションは、得意先コントローラにはありません。アクションが見つからない場合は、404を返します。ASP.Net Web APIは、別のルート・テンプレートを取るためにテンプレートlitstに再び戻されません。 – CodeNotFound

+0

あなたが言っているのは、ルート解決ではパラメータ名を考慮しないということです。最初にルートが選択され、次にパラメータがマッチします。あれは正しいですか? – Vikas

関連する問題