How to return multiple values from a C# WebAPI?

Viewed 4733

I have a Web API Endpoint with the following signatures.

 [HttpGet]
 [Route("api/some-endpoint")]
 public IHttpActionResult getAll()
 {
 ...
 ...
    return Ok({ firstList, secondList });
 }

Now, I want to return two list variables firstList, secondList. How to do that?

2 Answers

Return an anonymous type; all you're missing is the word new in your code:

 [HttpGet]
 [Route("api/some-endpoint")]
 public IHttpActionResult getAll()
 {
 ...
 ...
    return Ok(new { firstList, secondList });
 }

To rename the properties:

 [HttpGet]
 [Route("api/some-endpoint")]
 public IHttpActionResult getAll()
 {
 ...
 ...
    return Ok(new { propertyName1=firstList, propertyName2=secondList });
 }

Why not a Tuple, as advocated in the other answer? If you use Tuple your property name are fixed to the name of the Tuple properties (you'll end up with JSON like { "Item1": [ ... ] ...

you can do this with system.tuple or create a new class or structure like :

public class TheClass
{
public TheClass(List<string> f,List<string> l)
{
firstList = f;
secendList = l;
}
public List<string> firstList;
public List<string> secendList;
}

and

 [HttpGet]
 [Route("api/some-endpoint")]
 public IHttpActionResult getAll()
 {
 ...
 ...
    return new TheClass(firstList, secondList);
 }

But this class must be on clients to be able to receive and work with it

Related