Routing with multiple Get methods in ASP.NET Web API

前端 未结 10 846
闹比i
闹比i 2020-11-27 10:13

I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

I have 4 get meth

10条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 11:03

    From here Routing in Asp.net Mvc 4 and Web Api

    Darin Dimitrov has posted a very good answer which is working for me.

    It says...

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

提交回复
热议问题