找到多个与Web Api中的请求匹配的操作 [英] Multiple actions were found that match the request in Web Api

查看:162
本文介绍了找到多个与Web Api中的请求匹配的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用2种获取方法时,我不断收到此错误

I keep getting this error when I try to have 2 "Get" methods


发现有多个与请求相符的动作:webapi

Multiple actions were found that match the request: webapi

我一直在寻找关于堆栈的其他类似问题,但我不明白。

I been looking around at the other similar questions about this on stack but I don't get it.

我有2个不同的名称,并使用 HttpGet属性

I have 2 different names and using the "HttpGet" attribute

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

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


推荐答案

您的路线图可能是像这样:

Your route map is probably something like this:

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

但是要使用相同的http方法执行多个操作,您需要通过以下方式为webapi提供更多信息:像这样的路线:

But in order to have multiple actions with the same http method you need to provide webapi with more information via the route like so:

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

Notice that the routeTemplate now includes an action. Lots more info here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

更新:

好的,现在我想我明白您的意思,这是另一种看法:

Alright, now that I think I understand what you are after here is another take at this:

也许您不需要action url参数,并且应该以其他方式描述您要查找的内容。既然您说方法是从同一个实体返回数据,那么只需让参数为您做描述即可。

Perhaps you don't need the action url parameter and should describe the contents that you are after in another way. Since you are saying that the methods are returning data from the same entity then just let the parameters do the describing for you.

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

For example your two methods could be turned into:

public HttpResponseMessage Get()
{
    return null;
}

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

您要在MyVm对象中传递什么样的数据?如果您能够仅通过URI传递变量,我建议您采用该路线。否则,您将需要在请求的主体中发送该对象,而在执行GET时,该对象不是HTTP的对象(不过,可以,只需使用MyVm的[FromBody] infront)即可。

What kind of data are you passing in the MyVm object? If you are able to just pass variables through the URI, I would suggest going that route. Otherwise, you'll need to send the object in the body of the request and that isn't very HTTP of you when doing a GET (it works though, just use [FromBody] infront of MyVm).

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

Hopefully this illustrates that you can have multiple GET methods in a single controller without using the action name or even the [HttpGet] attribute.

这篇关于找到多个与Web Api中的请求匹配的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆