【问题标题】:AmbiguousActionException in same controller for different routes同一控制器中针对不同路由的 AmbiguousActionException
【发布时间】:2019-07-18 05:16:44
【问题描述】:

我有一个控制器得到 AmbiguousActionException。我有 3 种方法要执行 1.根据ID获取会员 2.找到所有具有某种眼睛颜色的成员 3. 获取所有成员

第一个工作正常,但我假设 2 和 3 得到 AmbiguousActionException,因为它们都只使用 HTTPGet 而没有别的。有没有一种方法可以区分带有查询参数的默认 HTTPGet 和 HTTPGet。我使用查询参数作为眼睛颜色过滤条件,而不是成员的键。

这是我的代码:

namespace MyController.Controllers
{
    [Route("members")]
    public class MemberController: Controller
    {
        [HttpGet("{memberId}")]
        public IActionResult GetMemberFor(string memberId)
        {
            return Ok(DoSomeMethodWithId(memberId));
        }

        [HttpGet(Name = "FindMembersWith")]
        public IActionResult FindMembersFor([FromQuery(Name = "eyeColor")] string eyeColor)
        {
            return Ok(DoSomeOtherMethodWithFilter(eyeColor);
        } 

        [HttpGet(Name = "GetAllMembers")]
        public IActionResult GetAllMembers()
        {
            return Ok(DoMethodToRetrieveAllMembers);
        }
    }
}

urls:
www.mysite.com/members/{id} -- get single member by id
www.mysite.com/members  -- get all members
www.mysite.com/members?eyeColor=blue  --get all members with blue eyes

我可以添加一些东西来使第 2 条和第 3 条路线正常工作吗?

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc


    【解决方案1】:

    您可以添加自定义路线:

    [Route("FindMembersWith")]
    [HttpGet]
    public IActionResult FindMembersFor([FromQuery(Name = "eyeColor")] string eyeColor)
    {
       return Ok(DoSomeOtherMethodWithFilter(eyeColor);
    } 
    
    [Route("GetAllMembers")]
    [HttpGet]
    public IActionResult GetAllMembers()
    {
        return Ok(DoMethodToRetrieveAllMembers);
    }
    

    【讨论】:

    • 我希望我的网址看起来像:www.mysite.com/members 和 www.mysite.com/members?eyeColor=blue。这不可能吗?
    • 我确实发现了一些有用的东西:stackoverflow.com/questions/46477959/…
    • 虽然这会起作用,但这不是 OP 所要求的。他们希望同一条路线处理两种不同的情况。当然,您可以简单地使用两条不同的路线。这并不是真正的开创性信息。
    猜你喜欢
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2016-03-29
    • 1970-01-01
    • 2014-06-18
    • 2015-10-09
    相关资源
    最近更新 更多