ApiController与int或string URI params相同的路由

时间:2014-10-28 16:47:39

标签: c# asp.net asp.net-apicontroller

我希望我的控制器能够根据相同变量名的数据类型来扩展端点。例如,方法A采用int,方法B采用字符串。我不想声明一个新的路由,而是要路由机制来区分整数和字符串。这是我的意思的一个例子。

“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 个答案:

答案 0 :(得分:1)

您可以尝试以下可能的解决方案。

//Solution #1: If the string (id) has any numeric, it will not be caught.
//Only alphabets will be caught
public class StringBaseApiController: BaseApiController
{
 [HttpGet]
 [Route("{id:alpha}")]
 public HttpResponseMessage GetEntity(string id){}
}
//Solution #2: If a seperate route for {id:Int} is already defined, then anything other than Integer will be caught here.
public class StringBaseApiController: BaseApiController
{
 [HttpGet]
 [Route("{id}")]
 public HttpResponseMessage GetEntity(string id){}
}

答案 1 :(得分:-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);
        }

}