2014-10-28 31 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

相关问题