【问题标题】:Multiple actions were found that match the request (GET)找到与请求匹配的多个操作 (GET)
【发布时间】:2013-04-01 21:08:05
【问题描述】:

我在我的控制器中定义了 2 个 GET 方法,一个名为“Favorites”,另一个简单地命名为“Get”。在我的路由中,我专门将不同的 URL 路由映射到这两种不同的方法。

但是,当我点击 /Api/MockUsers/Get?userId=2 时,我收到以下错误:

找到多个匹配请求的操作

但是,当我点击 /api/MockUsers/1/favorites 时,它返回的数据就好了。

我很困惑,因为我似乎专门将 /Api/MockUsers/Get?userId=2 路由到 ACTION “Get”,而不是“Favorites”,那么为什么 MvC4 会感到困惑?

这就是我的路线的样子:

routes.MapHttpRoute(
       name: "Users",
       routeTemplate: "api/MockUsers/{id}/favorites",
       defaults: new { controller = "MockUsers", action = "Favorites", id = 1 }
);

routes.MapHttpRoute(
        name: "Api_Get",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { action = "Get", id = RouteParameter.Optional },
        constraints: new { httpMethod = new HttpMethodConstraint("GET") }
);

在我的控制器中,我有两种方法:

[AcceptVerbs("GET")]
public UserFavorite Favorites(long id)
{
   Favorite f = new Favorite(1, "Favorite 1", "Favorite Type 1");
   UserFavorite userFavorite = new UserFavorite(1, f);

   return userFavorite;
}

public User Get(long userId)
{
   User u = _mockusersService.GetUser(userId);
   return u;
}

【问题讨论】:

  • nuget.org/packages/routedebugger 可能会有所帮助
  • 您将通过命名动作Get、使用GET HTTP 动词来调用它而不是归因于动作来混淆web api。按照惯例,Web API 会认为您的 Get 操作应该由 HTTP 动词调用。因此,使用网址:/Api/MockUsers?userId=2
  • ASP.NET Web api 不能在同一个 ApiController 中混合使用“传统”和基于动词的路由。这记录在 codeplex (aspnetwebstack.codeplex.com/workitem/184) 上,最简单的解决方案是摆脱你的 get 操作。或者您可以关注这篇文章 (blog.appliedis.com/2013/03/25/…) 并 (i) 硬编码默认值,而不是指定该操作是可选的,(ii) 用硬编码的默认动作名称装饰你的“基于动词的控制器”

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


【解决方案1】:

您可以使用默认的 Webapi 路由来执行此操作,但要更改查询方式。 WebApiConfig.cs 中的默认路由:

configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
   new { id = RouteParameter.Optional });

假设 webapi 控制器名为 MockUsers,示例调用的行为如下:

GET /Api/MockUsers?userId=2444 -->将解析为以 userId 作为参数的 GET 方法(您的 Get 方法端点)。

GET /Api/MockUsers?id=23444 -->将解析为以 Id 作为参数的 GET 方法(您最喜欢的方法端点)。

【讨论】:

    猜你喜欢
    • 2016-04-08
    • 1970-01-01
    • 2018-11-04
    • 2017-01-07
    • 2015-05-01
    • 2016-07-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    相关资源
    最近更新 更多