且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找到多个与Web Api中的请求匹配的操作

更新时间:2023-02-15 13:12:42

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

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.