[SOLVED] Retrieve object with two different attributes in ASP.NET REST-API

Issue

I have a REST API in ASP.NET to CRUD persons. The Person class looks like this:

class Person
{
    private int id;
    private string name;
    private int age;
    private string email;
}

I can already retrieve a person by id using the following route:

[HttpGet]
[Route("person/{personId}")]
public IActionResult Person(int personId)
{
    // This code doesn't matter
    var person = _personManager.Get(personId);
    if (person is null) return NotFound("Person not found");
            
    return Ok(person.ToDto());
}

But the problem is that I also want to retrieve a person by it’s e-mail. How would I do that? Is this an option?


// Could this work?
[HttpGet]
[Route("person/email/{personEmail}")]
public IActionResult Person(string email)
{
    // This code doesn't matter
    var person = _personManager.GetByMail(personEmail);
    if (person is null) return NotFound("Person not found");
            
    return Ok(person.ToDto());
}

Or is there a better way to do this? The current route [Route("person/{personId}")] can’t be altered though because it’s already used a lot.

Thanks.

Solution

Try this:

[Route("person/{id}")]
[Route("personById/{id}")]
public IActionResult GetPersonById(int id)
{
    // This code doesn't matter
    var person = _personManager.Get(id);
    if (person is null) return NotFound("Person not found");
            
    return Ok(person.ToDto());
}

[Route("personByEmail/{email}")]
public IActionResult GetPersonByEmail(string email)
{
    // This code doesn't matter
    var person = _personManager.GetByMail(personEmail);
    if (person is null) return NotFound("Person not found");
            
    return Ok(person.ToDto());
}

Answered By – Serge

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *