asp.net-mvc Asp.net Mvc 4 和 Web Api 中的路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12775887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:19:55  来源:igfitidea点击:

Routing in Asp.net Mvc 4 and Web Api

asp.net-mvcasp.net-mvc-4asp.net-mvc-routingasp.net-web-api

提问by Yasser Shaikh

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:ApiControllerand I wish to have the following

由控制器说是 =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

  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

请帮我解决这个问题。谢谢

回答by Darin Dimitrov

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

回答by Amit Halder - Web Spiders

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