ApiController - same route for int or string URI parameters

I would like my controllers to extend endpoints based on the datatype of the same variable name. For example, method A takes an int and method B takes a string. I don't want to declare a new route, but rather for a routing mechanism to differentiate between targets and strings. Here's an example of what I mean.

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

      

The following route has been added to "WebApionfig.cs":

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

      

I want to call "http://controller/1"

and "http://controller/one"

and get the results. Instead, I see an exception with multiple routes.

+3


source to share


2 answers


You can try the following possible solutions.



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

      

0


source


Use only string and check inside if you have int or string or any other thing and call the appropriate method.



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);
        }

}

      

-2


source







All Articles