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


Solution 1:

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