C# Web API 如何返回多种类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11733205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How Web API returns multiple types
提问by Matt
I am just wondering whether it is possible to return multiple types in a single Web Api. For example, I want an api to return both lists of customers and orders (these two sets of data may or may not relate to each other?
我只是想知道是否可以在单个 Web Api 中返回多种类型。例如,我想要一个 api 返回客户列表和订单(这两组数据可能相互关联,也可能不相关?
采纳答案by cuongle
To return multiple types, you can wrap them into anonymous type, there are two possible approaches:
要返回多个类型,可以将它们包装成匿名类型,有两种可能的方法:
public HttpResponseMessage Get()
{
var listInt = new List<int>() { 1, 2 };
var listString = new List<string>() { "a", "b" };
return ControllerContext.Request
.CreateResponse(HttpStatusCode.OK, new { listInt, listString });
}
Or:
或者:
public object Get()
{
var listInt = new List<int>() { 1, 2 };
var listString = new List<string>() { "a", "b" };
return new { listInt, listString };
}
Also remember that The XML serializer does not support anonymous types. So, you have to ensure that request should have header:
还要记住XML 序列化程序不支持匿名类型。所以,你必须确保请求应该有标头:
Accept: application/json
in order to accept json format
为了接受json格式
回答by Anand
You have to use JsonNetFormatter serializer, because the default serializer- DataContractJsonSerializer can not serialize anonymous types.
你必须使用 JsonNetFormatter 序列化器,因为默认的序列化器 DataContractJsonSerializer 不能序列化匿名类型。
public HttpResponseMessage Get()
{
List<Customer> cust = GetCustomers();
List<Products> prod= GetCustomers();
//create an anonymous type with 2 properties
var returnObject = new { customers = cust, Products= prod };
return new HttpResponseMessage<object>(returnObject , new[] { new JsonNetFormatter() });
}
You could get JsonNetFormatter from HERE
你可以从这里得到 JsonNetFormatter
回答by codechecker
Instead of this:
取而代之的是:
return ControllerContext.Request
.CreateResponse(HttpStatusCode.OK, new { listInt, listString });
use this:
用这个:
return Ok(new {new List<int>() { 1, 2 }, new List<string>() { "a", "b" }});

