同一控制器中针对不同路由的AmbiguousActionException

时间:2019-02-24 19:00:44

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

我有一个控制器正在获取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

我可以添加一些东西来使第二条和第三条路线起作用吗?

1 个答案:

答案 0 :(得分: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);
}