How to return multiple values from a C# WebAPI?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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": [ ... ] ...

Method 2

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x