Archer_A Archer_A - 3 years ago 101
C# Question

WebAPI Controller GetAll or Get some Id

I have a controller like this

[Route("api/Foo/MyController/{id}")]
public IHttpActionResult Get(int id)
{
//Code code
foo(id); // Foo accept Int or Null
}


This do work, if call api/Foo/MyController/1, but i needed call api/Foo/MyController like it "GetAll" the parameter id now is null and the stuff into controller return all, how go there?

Answer Source

You could do also a optional parameter:

[Route("api/Foo/MyController/{id}")]
public IHttpActionResult Get(int? id = null)
{
    IQueryable foo = GetData();
    if (id.HasValue)
    {
        foo = foo.Where(e => e.Id == id.Value);
    }
    //...
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download