37

我可以同时使用以下两个路由规则吗?

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,我希望有以下

  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

请帮助我。谢谢

4

2 回答 2

57

你可以有几条路线:

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" }
        );
    }
}
于 2012-10-08T07:01:50.460 回答
0
config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );
于 2016-04-21T06:24:27.233 回答