如何从 C# WebAPI 返回多个值?

Muh*_*ooq 5 .net c# asp.net asp.net-web-api2

我有一个具有以下签名的 Web API 端点。

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

现在,我想返回两个列表变量firstList、secondList。怎么做?

Cai*_*ard 6

返回匿名类型;new您所缺少的只是代码中的单词:

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

要重命名属性:

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

为什么不像另一个答案中所提倡的那样使用元组?如果您使用 Tuple,您的属性名称将固定为 Tuple 属性的名称(您最终会得到类似 JSON{ "Item1": [ ... ] ...