我只是想知道是否可以在一个Web Api中返回多个类型。例如,我希望api同时返回客户列表和订单列表(这两组数据可能相互关联,也可能不相关?
发布于 2012-07-31 05:24:38
要返回多个类型,可以将它们包装到匿名类型中,有两种可能的方法:
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 });
}
或者:
public object Get()
{
var listInt = new List<int>() { 1, 2 };
var listString = new List<string>() { "a", "b" };
return new { listInt, listString };
}
还要记住,XML序列化程序不支持匿名类型。因此,您必须确保请求应该具有报头:
Accept: application/json
为了接受json格式
发布于 2012-07-31 04:50:20
您必须使用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() });
}
您可以从HERE获得JsonNetFormatter
发布于 2020-04-15 20:16:36
而不是这样:
return ControllerContext.Request
.CreateResponse(HttpStatusCode.OK, new { listInt, listString });
使用以下命令:
return Ok(new {new List<int>() { 1, 2 }, new List<string>() { "a", "b" }});
https://stackoverflow.com/questions/11733205
复制