当我尝试有2个“Get”方法时,我一直得到这个错误

发现了多个与请求:webapi匹配的操作

我一直在看其他类似的问题,但我不明白。

我有2个不同的名字,并使用“HttpGet”属性

[HttpGet]
public HttpResponseMessage Summary(MyVm vm)
{
    return null;
}

[HttpGet]
public HttpResponseMessage FullDetails()
{
    return null;
}

当前回答

由于使用MVC控制器而不是Web API控制器,这是可能的。 检查Web API控制器中的命名空间,它应该如下所示

using System.Net;
using System.Net.Http;
using System.Web.Http;

如果命名空间如下所示,则在web api控制器方法调用时给出上述错误

using System.Web;
using System.Web.Mvc;

其他回答

从Web API 2开始更新。

在WebApiConfig.cs文件中使用这个API配置:

public static void Register(HttpConfiguration config)
{
    //// Web API routes
    config.MapHttpAttributeRoutes(); //Don't miss this

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

你可以像这样路由我们的控制器:

[Route("api/ControllerName/Summary")]
[HttpGet]
public HttpResponseMessage Summary(MyVm vm)
{
    return null;
}

[Route("api/ControllerName/FullDetails")]
[HttpGet]
public HttpResponseMessage FullDetails()
{
    return null;
}

其中ControllerName是控制器的名称(没有“controller”)。这将允许您使用上面详细介绍的路由获取每个操作。

欲进一步阅读:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

经过大量的网络搜索,并试图找到最适合的形式的路由地图 如果发现了以下情况

config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id =RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");

这些映射适用于动作名称映射和基本的http约定(GET,POST,PUT,DELETE)

有可能你的webmethods被解析为相同的url。请浏览以下连结:-

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

所以,你可能需要将你的methodname添加到路由表中。

由于使用MVC控制器而不是Web API控制器,这是可能的。 检查Web API控制器中的命名空间,它应该如下所示

using System.Net;
using System.Net.Http;
using System.Web.Http;

如果命名空间如下所示,则在web api控制器方法调用时给出上述错误

using System.Web;
using System.Web.Mvc;

在WebApiConfig.cs中,你的路线图可能是这样的:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });

但是为了让同一个http方法有多个动作,你需要通过路由为webapi提供更多的信息,如下所示:

routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });

注意,routeTemplate现在包含了一个动作。更多信息请访问:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

更新:

好吧,现在我想我明白你想要的是什么了,下面是另一个例子:

也许你不需要action url参数,而应该用另一种方式描述你想要的内容。既然你说的是方法从同一个实体返回数据,那么就让参数为你做描述。

例如,你的两个方法可以变成:

public HttpResponseMessage Get()
{
    return null;
}

public HttpResponseMessage Get(MyVm vm)
{
    return null;
}

在MyVm对象中传递什么类型的数据?如果你能够通过URI传递变量,我建议你走那条路。否则,你需要在请求的主体中发送对象,当你做一个GET时,这不是很HTTP(虽然它是有效的,只是在MyVm前面使用[FromBody])。

希望这说明了您可以在一个控制器中有多个GET方法,而不使用动作名称或甚至[HttpGet]属性。