1

I have a controller which gets data from a database but i want to have multiple methods [Actions] for the same GetAll Method based on different key.

Example

consider this DB

enter image description here

can i have a controller with different GetAll method based on CountryID, AddressID, DepartmentID like this

   [ApiController]
    [Route("api/Users")]
    public class UsersController : ControllerBase
    {
      //Without a key
         [HttpGet]
        public IEnumerable<User> GetAll()
        {
            return repository.GetAll();
        }

         [HttpGet("{addressId}")]
        public async IEnumerable<User> GetAll([FromRoute]string addressId)
        {
            User user=  repository.GetAll(addressId);
         }

         [HttpGet("{CountryID}")]
        public async IEnumerable<User> GetAll([FromRoute]string CountryID)
        {
            User user=  repository.GetAll(CountryID);
         }

         [HttpGet("{DepartmentID }")]
        public async IEnumerable<User> GetAll([FromRoute]string DepartmentID ) 
        {
            User user=  repository.GetAll(DepartmentID );
         }

    }

and if i can how can i call this different method from the http request.

thanks in advance

1
  • Why don't you use ViewModel to filter data? A ViewModel that contains CountryID, AddressID and DepartmentID . Commented Aug 16, 2022 at 16:09

1 Answer 1

3

You can define routing rules like below:

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    // Without a key
    [HttpGet]
    // GET /api/Users
    public IEnumerable<User> Get()
    {
        return repository.GetAll();
    }

    [HttpGet("AddressId/{id}")]
    // GET /api/Users/AddressId/123
    public IEnumerable<User> GetByAddressIdAll([FromRoute] int id)
    {
        ....
    }

    [HttpGet("CountryId/{id:int}")]
    // GET /api/Users/CountryId/456
    public IEnumerable<User> GetByCountryIdAll([FromRoute] int id)
    {
        ....
    }

    [HttpGet("DepartmentID/{id:int}")]
    // GET /api/Users/DepartmentId/678
    public IEnumerable<User> GetByDepartmentIdAll([FromRoute] int id)
    {
        ....
    }
}

See the documentation: Attribute routing with Http verb attributes

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.