ApiController与int或字符串URI参数的路由相同

本文关键字:路由 参数 URI int 字符串 ApiController | 更新日期: 2023-09-27 18:28:05

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

"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){}
}

"WebAponfig.cs"添加了以下路由:

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

我想调用"http://controller/1""http://controller/one"并获取结果。相反,我看到了多路由异常。

ApiController与int或字符串URI参数的路由相同

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

//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){}
}

只使用字符串,并在内部检查是否获得了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);
        }
}