2016-11-28 20 views
0

我有控制器,各種動作,其中之一是:多的行動中發現匹配的WebAPI請求

[HttpGet] 
public IList<string> GetFoo(string id = null) 
{ ... } 

這個動作有個別路線:

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

當我添加另一個動作:

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

請求到localhost/API /我/富/失敗:

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" 

有人可以解釋爲什麼會發生這種情況?我爲api/my/foo指定了action =「GetFoo」,爲什麼它與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} 
); 

如果是這樣,第一條路線不符和下降罰球默認路由,但缺省路由多個動作匹配。

注:如果您使用ID請求明確 GetFoos路線將工作 - /api/my/foo/1


理想的情況下,如果使用過多的定製路由看到你自己,你可能要考慮使用路由屬性可用於Web API 2,而不是在Route config中創建單個路由。

例如,

[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}; 
    } 
} 
相關問題