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

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

问题描述

当我尝试使用 2 个Get"方法时,我不断收到此错误

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;
}

推荐答案

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

Your route map is probably something like this in WebApiConfig.cs:

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]).

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天全站免登陆