Search code examples
asp.net-web-api-routing

Can I overload a Web API get call?


I'm trying to set up my Web API app to be able to accept something like

/api/product/1 where 1 is the ID and something like /api/product/somestringidentifier

The latter I can not get to hit my Get(string alias) method. The (int id) and GetProducts() work fine.

Routes

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "AliasSelector",
                routeTemplate: "api/{controller}/{alias}"
            );

Controller

[AcceptVerbs("GET")]
 public IProduct Get(int id)
 {
    return new Product(id);
 }
 [AcceptVerbs("GET")]
 public IProduct Get(string alias)
 {
     return new Product(alias);
 }
 [AcceptVerbs("GET")]
 [ActionName("Products")]
 public IEnumerable<IProduct> GetProducts()
 {
      return new Products().ToList();
 }

Solution

  • Assuming that your id is always going to be an integer and alias is always going to be a string, you could try adding route constraints like so:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id = @"\d*" }
    );
    
    config.Routes.MapHttpRoute(
        name: "AliasSelector",
        routeTemplate: "api/{controller}/{alias}",
        constraints: new { alias= @"[a-zA-Z]+" }
    );