Asp.net Web API:控制器上未找到任何操作

时间:2012-12-27 16:55:39

标签: asp.net-web-api asp.net-web-api-routing

我正在使用Visual Studi0 2010.在我的WebApiConfig.cs文件中,我有以下配置,我可以映射这两个网址/Values/Values/1。它工作正常。

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {id= RouteParameter.Optional  } 
        );

由于我想使用/Values/Machines/Values/Machines/100这样的自定义网址,因此我将上述设置更改为以下设置。

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new {action="get", id= RouteParameter.Optional  } 
        );

现在,除了这个/Values/1之外,它现在映射到网址下方。请让我知道我错过了什么。

1./Values
2./Values/Machines
3./Values/Machines/100

感谢。

1 个答案:

答案 0 :(得分:2)

这是预期的行为。根据您的新Route,第一个参数Values应该是Controller名称,第二个参数1应该是一个Action,但是您没有名为{{1的操作}}

为了获得行动,你需要带有新路线的网址如下:1

你可以这样做:

/Values/Index/1

在这种情况下,如果网址如下:routes.MapRoute( name: "IndexWithParam", url: "{controller}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, constraints: new { id = @"\d+" } ); routes.MapRoute( name: "Default", // Route name url: "{controller}/{action}/{id}", // URL with parameters defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); ,它会点击第一条路线并将其重定向到/Values/1。请注意,我在此路线上设置了一个约束,以确保第二个参数是一个数字。

相关问题