Can I use two or more HttpGet requests in the same controller in ASP.NET Core API?

Viewed 179

I have just start out using ASP.NET Core API. Currently I have get All and get By ID. I have used a couple of nuget packages that built these for me. I want to be able to filter by ID and by name so that it is more user friendly.

Below is the controller:

namespace Manager_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ClientsController : ControllerBase
    {
        private readonly BelfastEatsContext _context;

        public ClientsController(BelfastEatsContext context)
        {
            _context = context;
        }

        // GET: api/Clients
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TblClient>>> GetTblClient()
        {
            return await _context.TblClient.ToListAsync();
        }

        //GET: api/Clients/5
        [HttpGet("{id?}")]
        public async Task<ActionResult<TblClient>> GetTblClient(int id)
        {
            var tblClient = await _context.TblClient.FindAsync(id);

            if (tblClient == null)
            {
                return NotFound();
            }

            return tblClient;
        }

A couple of things I have tried are:

        [HttpGet("{name}")]
        public async Task<ActionResult<TblClient>> GetTblClient(string name)
        {
            var tblClient = await _context.TblClient.FindAsync(name);

            if (tblClient == null)
            {
                return NotFound();
            }

            return tblClient;
        }

and

//GET: api/Clients/5
        [HttpGet("{id:int}")]
        public async Task<ActionResult<TblClient>> GetTblClient(int id)
        {
            var tblClient = await _context.TblClient.FindAsync(id);

            if (tblClient == null)
            {
                return NotFound();
            }

            return tblClient;
        }

I am so stuck so any help would be amazing.

Thank you

2 Answers

Yes, you can have multiple Get Action methods in the controller as long as their names are different. By name, I mean method name and its route

Try it like this :

    [Route("GetTblClient/{name}")]
    public async Task<ActionResult<TblClient>> GetTblClient(string name)
    {
        var tblClient = await _context.TblClient.FindAsync(name);

        if (tblClient == null)
        {
            return NotFound();
        }

        return tblClient;
    }

UPADTE

you can use another query depending on your Model

var tblClient = await _context.TblClient.where(a => a.ClientName.Equals(name)).FirstOrDefaultAsync();
Related