C
C#2y ago
Manson

How to differentiate endpoints based on parameters?

I want to have two endpoints /users and /users?id=#, but swagger doesn't seem to like what I have now. I really don't want to have to make an endpoint just because it can't differentiate between the two. Tips would be appreciated.
c#
// GET - "https://localhost:7229/api/users"
[HttpGet]
public async Task<IActionResult> GetAllUsers();

// GET - "https://localhost:7229/api/users?=#"
[HttpGet]
public async Task<IActionResult> GetUserById([FromQuery] int id);

c#
// GET - "https://localhost:7229/api/users"
[HttpGet]
public async Task<IActionResult> GetAllUsers();

// GET - "https://localhost:7229/api/users?=#"
[HttpGet]
public async Task<IActionResult> GetUserById([FromQuery] int id);

3 Replies
Saber
Saber2y ago
have the second route be different. ie /api/users/1
Manson
MansonOP2y ago
I can't use query params without changing the endpoint? I know I can just do api/users/1 but I would like to be able to user api/users?=1 I guess I should ask is there a way to use the same url but differentiate by the use of query params? Coming from springboot you could do that so I was just wondering if there was an equivalent.
// /users
@GetMapping()
public User[] getAll() {
return users;
}

// /[email protected]&password=password
@GetMapping(params={"email", "password})
public User getByEmailAndPassword(
@RequestParam String email, // email
@RequestParam String password // password
) {
// Do whatever
return user;
}
// /users
@GetMapping()
public User[] getAll() {
return users;
}

// /[email protected]&password=password
@GetMapping(params={"email", "password})
public User getByEmailAndPassword(
@RequestParam String email, // email
@RequestParam String password // password
) {
// Do whatever
return user;
}
pwillt
pwillt2y ago
This is more of a problem with http standards, your trying to use /users for a single and multi result endpoints. I'm wondering why your not using /users and /user. If you really want to use /users for both you could use the same method: [HttpGet] [Route("/users")] public object[] get(string email, string password) { if (string.IsNullOrWhiteSpace(email) && string.IsNullOrWhiteSpace(password)) { return new object[1]; } else { return new object[0]; } }
Want results from more Discord servers?
Add your server