我可以一起使用以下两个路由规则吗?
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 } );
说控制器是= FruitApiController:ApiController和我希望有以下
> List< Fruit> Get()= api / FruitApi /
> List< Fruit> GetSeasonalFruits()= api / FruitApi / GetSeasonalFruit
> Fruit GetFruits(string id)= api / FruitApi / 15
> Fruit GetFruitsByName(string name)= api / FruitApi / GetFruitsByName / apple
请帮我这个。谢谢
解决方法
你可以有几个路线:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "ApiById",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" } ); } }