2016-11-28 1 views
0

WEBAPI内の要求と一致する発見されました:複数のアクションは、私はさまざまなアクションとコントローラーを持っており、そのうちの一つがある

[HttpGet] 
public IList<string> GetBar() 
{ ... } 

要求がlocalhostに/ API /私の/ fooが/失敗:

Multiple actions were found that match the request: 
↵System.Collections.Generic.IList`1[System.String] GetFoo(System.String) on type Controllers.MyController 
↵System.Collections.Generic.IList`1[System.String] GetBar() on type Controllers.MyController" 

なぜこのようなことが起こりますか?私は、action = "GetFoo"をapi/my/fooに指定しました。なぜそれがGetBarにマッチするのですか?

答えて

2

次のように経路を設定し、IDなしでリクエストすることができます(/api/my/foo)。

config.Routes.MapHttpRoute(
    name: "GetFoos", 
    routeTemplate: "api/my/foo/{id}", 
    defaults: new {controller = "My", action = "GetFoo"} 
); 

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

もしそうなら、最初のルートはと秋の経路をデフォルトに投げると一致していませんが、デフォルトルートが複数のアクションと一致します。

注: GetFoosルートを明示的にIDを要求した場合に動作します - /api/my/foo/1理想的


、あなた自身があまりにも多くのカスタムルートを使用して見れば、あなたはルート属性を使用して検討する必要がありますをWeb API 2で使用できるようになりました。ルート設定で個々のルートを作成するのではなく、例えば

[RoutePrefix("Api/My")] 
public class MyController : ApiController 
{ 
    [HttpGet] 
    [Route("foo/{id:int}")] 
    public IList<string> GetFoo(int id) 
    { 
     return new string[] {"Foo1-" + id, "Foo1-" + id}; 
    } 

    [HttpGet] 
    [Route("bar/{id:int}")] 
    public IList<string> GetBar(int id) 
    { 
     return new string[] {"Bar1-" + id, "Bar1-" + id}; 
    } 
} 
関連する問題