WebAPI multiple HTTPGET from PostMan, multiple matching endpoint error

Viewed 294

In my webAPI I have 3 HTTPGET controller methods. Here is what I can calling from google postman and the method so far

selected GET postman with http://localhost:51970/user
successfully calls API: public ActionResult<IEnumerable<User>> Get()

selected GET postman with http://localhost:51970/user/1
successfully calls API: public ActionResult<User> Get(int id)



I tried string parameter but get multiple matching GET endpoints
[HttpGet("{code}")]
I tried public ActionResult<User> Get(string name) 

but getting this error

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches:

it can't tell the difference from the other GET calls.

I would like to pass a string to pass to the query by name property.

Any help is appreciated. Thanks

Here is my API

    [Route("[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {

        private readonly IUserService userService;

        public UserController (IUserService _userService)
        {
            userService= _userService;
        }

        [HttpGet]
        public ActionResult<IEnumerable<User>> Get()
        {
                var users= userService.GetUsers();
                return Ok(users);
        }

        [HttpGet("{id}")]
        public ActionResult<User> Get(int id)
        {
                var user= userService.GetUserById(id);
                return Ok(user);
        }


        [HttpGet("{code}")]
        public ActionResult<User> Get(string name)
        {
                var user= claimService.GetUserByName(name);
                return Ok(user);
        }
}
1 Answers

You need to differ between your Get-methods, that can be done by modifying route for Get(int id) with [HttpGet("{id:int}")] like this

    [HttpGet("{id:int}")]
    public ActionResult<User> Get(int id)
    {
      var user= userService.GetUserById(id);
      return Ok(user);
    }

    [HttpGet("{code}")]
    public ActionResult<User> Get(string code)
    {
      var claimf = claimService.GetClaimsByCode(code);
      return Ok(claimf);
    }

Tested and verified on my computer.

Related