2014-10-28 26 views
3

我希望我的控制器根據相同變量名稱的數據類型來擴展端點。例如,方法A接受一個int,方法B接受一個字符串。我不想聲明新的路由,而是要求路由機制區分整數和字符串。這是我的意思的一個例子。ApiController對於int或字符串URI參數的相同路由

的 「ApiControllers」 設置:

public class BaseApiController: ApiController 
{ 
     [HttpGet] 
     [Route("{controller}/{id:int}")] 
     public HttpResponseMessage GetEntity(int id){} 
} 

public class StringBaseApiController: BaseApiController 
{ 

     [HttpGet] 
     [Route("{controller}/{id:string}")] 
     public HttpResponseMessage GetEntity(string id){} 
} 

的 「WebApionfig.cs」 有以下途徑補充說:

config.Routes.MapHttpRoute(
    "DefaultApi", 
    "{controller}/{id}", 
    new { id = RouteParameter.Optional } 
); 

我想打電話給"http://controller/1""http://controller/one",並得到結果。相反,我看到了多重路線例外。

+2

你在你的webapiconfig中調用'config.MapHttpAttributeRoutes();',對吧? – 2014-10-28 16:49:44

+0

您是否嘗試刪除默認路由或將您的參數更改爲id以外的其他名稱?目前你的屬性路由與你正在定義的「正常」默認路由發生衝突。 – 2014-10-28 16:54:19

+0

重複http://stackoverflow.com/questions/2710454/asp-net-mvc-can-i-have-multiple-names-for-the-same-action – dariogriffo 2014-10-28 17:00:38

回答

-2

只使用字符串,並檢查裏面是否有int或字符串或其他任何東西並調用適當的方法。

public class StringBaseApiController: BaseApiController 
{ 

     [HttpGet] 
     [Route("{controller}/{id:string}")] 
     public HttpResponseMessage GetEntity(string id) 
     { 
      int a; 
      if(int.TryParse(id, out a)) 
      { 
       return GetByInt(a); 
      } 
      return GetByString(id); 
     } 

} 
+0

這不是真的有用,如果OP想要有多個行動,此外它仍然與默認路由衝突。 – 2014-10-28 16:55:43

+0

@BenRobinson他不能有兩個同名的動作。期間,我提供了一個替代方案。 http://stackoverflow.com/questions/2710454/asp-net-mvc-can-i-have-multiple-names-for-the-same-action – dariogriffo 2014-10-28 17:00:15

+0

您可以使用相同的路由和參數只有Web API 2和屬性路由的參數類型不同。該鏈接看起來相當過時。 – 2014-10-28 17:04:30

相關問題