37

Can I use the following two route rule together ?

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

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

Say by controller is = FruitApiController:ApiController and I wish to have the following

  1. List<Fruit> Get() = api/FruitApi/

  2. List<Fruit> GetSeasonalFruits() = api/FruitApi/GetSeasonalFruit

  3. Fruit GetFruits(string id) = api/FruitApi/15

  4. Fruit GetFruitsByName(string name) = api/FruitApi/GetFruitsByName/apple

Please help me on this. Thanks

Ivaylo Slavov
  • 8,839
  • 12
  • 65
  • 108
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • interesting. my guess would be that controller/id would use the default index() action. – Ammar Oct 08 '12 at 05:48
  • Possible duplicate of [Web Api Routing for multiple Get methods in ASP.NET MVC 4](http://stackoverflow.com/questions/12775590/web-api-routing-for-multiple-get-methods-in-asp-net-mvc-4) – Stephen Nov 18 '15 at 09:19

2 Answers2

57

You could have a couple of routes:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0
config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68