Home > database >  Asp.net Core Web Api Multiple Controller Method For Get All
Asp.net Core Web Api Multiple Controller Method For Get All

Time:08-19

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

CodePudding user response:

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

  • Related