Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net web api 带有操作参数的ASP.NET Web API路由_Asp.net Web Api - Fatal编程技术网

Asp.net web api 带有操作参数的ASP.NET Web API路由

Asp.net web api 带有操作参数的ASP.NET Web API路由,asp.net-web-api,Asp.net Web Api,在我的Web API项目的WebApiConfig.cs文件中,我已将默认路由映射替换为: config.Routes.MapHttpRoute( name: "ContActId", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); 因

在我的Web API项目的WebApiConfig.cs文件中,我已将默认路由映射替换为:

config.Routes.MapHttpRoute(
                name: "ContActId",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
        );
因为我想要控制器和动作的组合,而不是大量的get和post

问题是这个。我有一个控制器CityController,具有以下两个操作

[HttpGet]
        public HttpResponseMessage GenderCount()
        {
            //Validate session and fetch gender related data of the city
            return Request.CreateResponse(HttpStatusCode.OK, genderData);                
        }

        [HttpGet]
        public HttpResponseMessage GenderCount(string cityID)
        {
            //Validate session and fetch gender related data of the city
            return Request.CreateResponse(HttpStatusCode.OK, genderData);                
        }

{HostName}/api/City/GenderCount?cityID=4api调用有效,但当我尝试以{HostName}/api/City/GenderCount/4格式发出相同的api调用时,它会转到不带参数的“GenderCount()”操作。

如果您已经有路由前缀

[RoutePrefix("api/City")]
在控制器上,尝试使用属性路由修饰方法

[Route("GenderCount/{cityID}"]

使用完整路径

[Route("api/City/GenderCount/{cityID}")]

我想知道为什么我的代码不美观。它无法映射
id
route参数。将动作参数从
string cityID
更改为
string id
,或者做相反的操作并更新路由本身。@Nkosi您的答案部分有效。在“反向”情况下,无法使用404 resource not found消息找到POST操作。为什么不将其作为实际答案而不是注释?正如您所建议的,即使在启用属性路由和修饰操作之后,也会调用无参数操作方法。我还验证了路由属性的名称空间,即“System.Web.Http”。它现在已修复。我不得不添加[Route(“api/City/GenderCount/{cityID}”)],而不仅仅是[Route({cityID}])。如果你相应地更新你的答案,我可以接受。可能您认为我的CityController已经有[RoutePrefix(“api/City”)]链接。@user1451111是的,我假设您有RoutePrefix。编辑了我的答案。