1

I would like to have a controller with multiple GET, one for all, one with int parameter and the other with a string parameter. The following example still give me error:

[ApiController]
[Route("[controller]")]
public class StudentsController : ControllerBase
{
    [HttpGet]
    public IEnumerable<Student> Get()
    {
        return GetStudents();
    }

    [HttpGet("{id}")]
    public Student Get(int id)
    {
        return GetStudents().FirstOrDefault(s=> s.id == id);
    }

    [HttpGet("{name}")]
    public Student Get(string name)
    {
        return GetStudents().FirstOrDefault(s=> s.name == name);
    }
}

EDIT Current I get the following error

enter image description here

1
  • what error do you get, please specify? Commented Nov 12, 2020 at 19:05

4 Answers 4

5

The int and string are treated equivalently in the url so it can't differentiate between the methods. You would need to either to have an additional part of the route, for example [HttpGet("id/{id}")] and [HttpGet("name/{name}")], or use query strings.

Alternatively you can have a single method and try parse the parameter into an int, if it succeeds, then retrieve by id, otherwise retrieve by name.

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

1 Comment

Only fix to this [HttpGet("id/{id}")] and [HttpGet("name/{name}")]
2

One way is like all of the other community members said,you could add additional part of the route to specify them.

Another way is that you could use Route constraint:

[HttpGet("{id:int}")]
public Student Get(int id)
{
}

[HttpGet("{name}")]
public Student Get(string name)
{
}

Comments

0

You should change your route action to this

[HttpGet("id/{id}")]
public Student Get(int id)
{
    return GetStudents().FirstOrDefault(s=> s.id == id);
}

[HttpGet("name/{name}")]
public Student Get(string name)
{
    return GetStudents().FirstOrDefault(s=> s.name == name);
}

Then you can call your action like this

/Students/name/john

/Students/id/123

Comments

-2

This is impossible since you have created ambiguous routes.
Try it like this:

[HttpGet("id/{id}")]
public Student Get(int id)
{
    return GetStudents().FirstOrDefault(s=> s.id == id);
}

[HttpGet("name/{name}")]
public Student Get(string name)
{
    return GetStudents().FirstOrDefault(s=> s.name == name);
}

1 Comment

It s a copy of the previous answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.