Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing in Asp.net Mvc 4 and Web Api

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

like image 651
Yasser Shaikh Avatar asked Oct 08 '12 05:10

Yasser Shaikh


1 Answers

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" }         );     } } 
like image 179
Darin Dimitrov Avatar answered Oct 23 '22 09:10

Darin Dimitrov