如何解决请求与 .Net Core Web Api 中的多个端点匹配的问题 [英] How do I resolve the issue the request matched multiple endpoints in .Net Core Web Api

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

问题描述

我注意到有很多关于这个主题的类似问题.

I notice that there are a bunch of similar questions out there about this topic.

我在调用以下任何方法时收到此错误.

I'm getting this error when calling any of the methods below.

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException:请求匹配多个端点.

但是,我无法弄清楚解决问题的最佳做法是什么.到目前为止,我还没有设置任何特定的路由中间件.

I can't however sort out what is best practice in resolving the issue. So far I haven't set up any specific routing middleware.

// api/menus/{menuId}/menuitems
[HttpGet("{menuId}/menuitems")]
public IActionResult GetAllMenuItemsByMenuId(int menuId)
{            
    ....
}

// api/menus/{menuId}/menuitems?userId={userId}
[HttpGet("{menuId}/menuitems")]
public IActionResult GetMenuItemsByMenuAndUser(int menuId, int userId)
{
    ...
}

推荐答案

您尝试执行的操作是不可能的,因为操作是动态激活的.在框架知道动作签名之前,无法绑定请求数据(例如查询字符串).在遵循路由之前,它无法知道动作签名.因此,你不能让路由依赖于框架甚至还不知道的东西.

What you're trying to do is impossible because the actions are dynamically activated. The request data (such as a query string) cannot be bound until the framework knows the action signature. It can't know the action signature until it follows the route. Therefore, you can't make routing dependent on things the framework doesn't even know yet.

无论是长还是短,您都需要以某种方式区分路由:要么是其他静态路径,要么是将 userId 设为路由参数.但是,这里实际上不需要单独的操作.默认情况下,所有操作参数都是可选的.因此,您只需:

Long and short, you need to differentiate the routes in some way: either some other static path or making the userId a route param. However, you don't actually need separate actions here. All action params are optional by default. Therefore, you can just have:

[HttpGet("{menuId}/menuitems")]
public IActionResult GetMenuItemsByMenu(int menuId, int userId)

然后您可以根据是否userId == 0(默认值)进行分支.在这里应该没问题,因为永远不会有 id 为 0 的用户,但您也可以考虑将参数设为可空,然后在 userId.HasValue 上分支,这更明确一些.

And then you can branch on whether userId == 0 (the default). That should be fine here, because there will never be a user with an id of 0, but you may also consider making the param nullable and then branching on userId.HasValue instead, which is a bit more explicit.

如果您愿意,您还可以通过使用私有方法继续保持逻辑分离.例如:

You can also continue to keep the logic separate, if you prefer, by utilizing private methods. For example:

[HttpGet("{menuId}/menuitems")]
public IActionResult GetMenuItems(int menuId, int userId) =>
    userId == 0 ? GetMenuItemsByMenuId(menuId) : GetMenuItemsByUserId(menuId, userId);

private IActionResult GetMenuItemsByMenuId(int menuId)
{
    ...
}

private IActionResult GetMenuItemsByUserId(int menuId, int userId)
{
    ...
}

这篇关于如何解决请求与 .Net Core Web Api 中的多个端点匹配的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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