5

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?

1
  • 2
    try with return Ok(new { firstList = firstList, secondList = secondList }); which will return a new object with two properties named firstList and secondList. Commented Dec 22, 2020 at 11:59

2 Answers 2

6

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

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

1 Comment

How would you deserialize the anonymous type on client side using JSON?
1

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

Comments

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.