[英]How to return multiple values from a C# WebAPI?
I have a Web API Endpoint with the following signatures.我有一个 Web API 具有以下签名的端点。
[HttpGet]
[Route("api/some-endpoint")]
public IHttpActionResult getAll()
{
...
...
return Ok({ firstList, secondList });
}
Now, I want to return two list variables firstList, secondList.现在,我想返回两个列表变量firstList、secondList。 How to do that?
怎么做?
Return an anonymous type;返回匿名类型; all you're missing is the word
new
in your code:您所缺少的只是代码中的
new
这个词:
[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": [... ]...
如果您使用 Tuple,您的属性名称将固定为 Tuple 属性的名称(您最终会得到 JSON,例如
{ "Item1": [... ]...
you can do this with system.tuple or create a new class or structure like:您可以使用system.tuple执行此操作或创建一个新的 class 或类似以下的结构:
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但是这个 class 必须在客户端才能接收和使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.