简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM