3

我希望我的控制器根据相同变量名的数据类型扩展端点。例如,方法 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"得到结果。相反,我看到了多路线异常。

4

2 回答 2

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){}
}
于 2018-04-20T17:29:18.497 回答
-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);
        }

}
于 2014-10-28T16:52:19.500 回答