Web api有两个获取动作

时间:2013-08-24 04:24:01

标签: c# asp.net-web-api asp.net-mvc-routing asp.net-web-api-routing

我有一个带有以下内容的测试控制器 -

        public string Get(int id)
        {
            return "hi from test " + id;
        }

        [HttpGet]
        public string Search(string text)
        {
            return "you searched for  " + text;
        }

我可以打电话

 - http://localhost:58635/api/Test/2
 - http://localhost:58635/api/Test?id=2
 - http://localhost:58635/api/Test/Search?text=textToSearcFor

但不是http://localhost:58635/api/Test/Search/textToSearcFor

我的路线与此post

中的路线相同
            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
        );

        config.Routes.MapHttpRoute(
            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );

我做错了什么?

1 个答案:

答案 0 :(得分:3)

对于“ApiByName”路线,请尝试更改

routeTemplate: "api/{controller}/{action}/{name}"

routeTemplate: "api/{controller}/{action}/{text}",

将“搜索”操作的参数名称“text”更改为“name”